视频观看地址:http://edu.51cto.com/course/14731.html
1、Spring程序分析
1.1、Spring管理Bean的原理
1.通过Resource对象加载配置文件;
2.解析配置文件,得到bean;
3.解析bean,id作为bean的名字,class用于反射得到bean的实例(Class.forName(className)); 这种配置下,所有的bean保证有一个无参数构造器
4.调用getBean的时候,从容器中返回对象实例
1.2、getBean方法的三种签名
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中只配置一个这种类型的实例(一个类型可能会产生多个对象,用的不多);
2.按照bean的名字拿bean,需要向下转型
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();
}
2、Spring中的测试
2.1、传统测试存在的问题
1、每个测试都要重新启动spring
2、测试代码在管理spring容器,应该是spring容器在管理测试代码
2.2、Spring测试
2.2.1、Spring测试模型图
2.2.2、操作步骤
1、添加jar包:
spring-test-4.3.14.RELEASE.jar
spring-aop-4.3.14.RELEASE.jar
junit-4.12.jar(junit版本更换为此版本)
2、编写测试类
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();
}
}