视频观看地址:http://edu.51cto.com/course/14731.htmlhtml
1.经过Resource对象加载配置文件;java
2.解析配置文件,获得bean;spring
3.解析bean,id做为bean的名字,class用于反射获得bean的实例(Class.forName(className)); 这种配置下,全部的bean保证有一个无参数构造器dom
4.调用getBean的时候,从容器中返回对象实例ide
1.按照类型拿bean测试
@Test public void test() { Resource resource = new ClassPathResource("SpringContext.xml"); BeanFactory factory = new XmlBeanFactory(resource); HelloWorld hw = factory.getBean(HelloWorld.class); hw.sayHello(); }
注意:若是使用此种方式要求在spring中只配置一个这种类型的实例(一个类型可能会产生多个对象,用的很少);spa
2.按照bean的名字拿bean,须要向下转型code
public void test() { Resource resource = new ClassPathResource("SpringContext.xml"); BeanFactory factory = new XmlBeanFactory(resource); HelloWorld world = (HelloWorld) factory.getBean("hello"); world.sayHello(); }
3.按照名字和类型视频
public void test() { Resource resource = new ClassPathResource("SpringContext.xml"); BeanFactory factory = new XmlBeanFactory(resource); HelloWorld world = factory.getBean("hello",HelloWorld.class); world.sayHello(); }
一、每一个测试都要从新启动springxml
二、测试代码在管理spring容器,应该是spring容器在管理测试代码
一、添加jar包:
spring-test-4.3.14.RELEASE.jar
spring-aop-4.3.14.RELEASE.jar
junit-4.12.jar(junit版本更换为此版本)
二、编写测试类
package cn.org.kingdom.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4Cla***unner; import cn.org.kingdom.hello.HelloWorld; //表示先启动Spring容器,把junit运行在Spring容器中 @RunWith(SpringJUnit4Cla***unner.class) //表示从哪里加载资源文件 @ContextConfiguration("classpath:SpringContext.xml") public class SpringTest { //表示自动装配 @Autowired private BeanFactory factory; @Test public void testSpringTest() throws Exception { HelloWorld helloWorld = factory.getBean("hello", HelloWorld.class); helloWorld.sayHello(); } }
注意:
若把@ContextConfiguration("classpath:SpringContext.xml") 写成@ContextConfiguration
默认去找的当前测试类名-context.xml, 这里配置文件如:SpringTest-context.xml
package cn.org.kingdom.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4Cla***unner; import cn.org.kingdom.hello.HelloWorld; @RunWith(SpringJUnit4Cla***unner.class) @ContextConfiguration public class SpringTest { @Autowired private BeanFactory factory; @Test public void testSpringTest() throws Exception { HelloWorld helloWorld = factory.getBean("hello", HelloWorld.class); helloWorld.sayHello(); } }