
2.4 SpringTest测试
前面通过ApplicationContext启动了Spring容器,并实现了配置文件的加载,但这样处理并不能体现出Spring的运行特征。为了更好地还原现实的开发场景,可利用SpringTest依赖库和JUnit实现测试环境下的Spring容器启动,且可以使用@Resource代替getBean方法实现自动注入。
1.【mldnspring项目】修改pom.xml配置文件,追加spring-test依赖库。

2.【mldnspring-base项目】修改pom.xml配置文件,在子模块中引入Spring相关测试依赖库。由于这里要基于JUnit工具实现测试,所以还需要引入junit测试依赖库。

3.【mldnspring-base项目】编写程序测试类。

本程序尽可能还原了Spring容器的实际运行环境。对它做如下几点说明。
@ContextConfiguration:表示Spring配置文件所在的目录。本程序通过classpath进行加载,由于src/main/resources属于源目录,所以目录中保存的所有资源将自动设置在CLASSPATH之中。
@RunWith(SpringJUnit4ClassRunner.class):表示要使用的测试工具类型。
@Resource:表示资源注入配置。首先会根据类型进行匹配,由于在spring-base.xml文件中配置的是MessageImpl子类,所以会自动与IMessage接口对应实现对象注入。如果有需要,也可以利用具体名称进行注入。
范例:设置具体的Bean名称。

@Resource注解中,代码name="messageImpl"中的名称就是spring-base.xml配置文件中<bean>元素id属性设置的名称。利用这种模式,可以避免一个接口、多个实例存在时无法匹配的问题。