視頻觀看地址: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(); } }