SPRING测试
环境:eclipse+tomcat 8.0 + spring 5.0
step 1:安装eclipse
step 2:安装web服务器
下载地址: https://tomcat.apache.org/whichversion.html
选择左侧的archive,从中选择8.0版本的tomcat(因为eclipse支持的最大版本tomcat是8.0)
具体下载目录为:https://archive.apache.org/dist/tomcat/tomcat-8/v8.0.50/bin/,选择下面的版本
apache-tomcat-8.0.50-windows-x64.zip
实际上没有安装过程,解压之后就可以使用。
step 3:安装spring 5.0
下载地址:http://repo.spring.io/release/org/springframework/spring/5.0.6.RELEASE/
实际上没有安装过程,解压之后就可以使用。但是,为了使用apache进行统一的日志管理,需要下载commons-logging-1.2.jar,下载地址为
http://commons.apache.org/proper/commons-logging/index.html
下载解压之后和上面的SPRING 包,一起导入。
step 4:编写测试代码
代码的目录结构如下:
AnimalDuck和AnimalCock都继承了ISingASong接口,在Animal类中有一个ISingASong接口属性。
ISingASong.java
package net.lightblue; public interface ISingASong { public String Sing(); }
AnimalDuck.java
package net.lightblue; public class AnimalDuck implements ISingASong { @Override public String Sing() { return "Hello World!"; } }
AnimalCock.java
package net.lightblue; public class AnimalCock implements ISingASong { @Override public String Sing() { return "world hello"; } }
Animal.java
package net.lightblue; public class Animal { private ISingASong singsong; public Animal() { } //带参构造器注入 public Animal(ISingASong singsong) { this.singsong = singsong; } public ISingASong getSingsong() { return singsong; } public void setSingsong(ISingASong singsong) { this.singsong = singsong; } public String sayHello() { return this.singsong.Sing(); } }
step 5: 注入
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="animalDuck" class="net.lightblue.AnimalDuck"></bean> <bean id="animalCock" class="net.lightblue.AnimalCock"></bean> <bean id="person" class="net.lightblue.Person"> <!-- 配置依赖关系 控制反转 get/set方法注入 --> <!-- <property name="singsong" ref="animalDuck"></property> --> <!-- 构造器注入 --> <constructor-arg ref="animalDuck" /> </bean> </beans>
这个XML文件需要放到和web.xml文件所在目录,服务器启动回去自动读取
step 6:测试类
package net.lightblue; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { System.out.println("begin"); AbstractApplicationContext context =new ClassPathXmlApplicationContext("animal.xml"); System.out.println("get person"); Animal person = (Animal) context.getBean("person"); System.out.println("run sayHello()"); String s = person.sayHello(); System.out.println(s); context.close(); System.out.println("end"); } }
ClassPathXmlApplicationContext类会自动到WEB-INF/classes目录下面找配置文件,所以需要将上面的配置文件放到这个目录下面
也可以通过XmlBeanFactory去读取,需要将上面配置文件放到工程的根目录下面
//引入配置文件 Resource r = new FileSystemResource("helloMessage.xml"); //加载配置文件 BeanFactory f = new XmlBeanFactory(r); //获取Person实例 Person person = (Person) f.getBean("person"); String s = person.sayHello();
posted on 2018-10-28 19:48 lightblueme 阅读(147) 评论(0) 编辑 收藏 举报