当类 AbstractDependencyInjectionSpringContextTests(及其子类)装载你的Application Context时,你可以通过Setter方法来注入你想要的来自context的bean,而不需要显式的调用applicationContext.getBean(XXX)。因为AbstractDependencyInjectionSpringContextTests会从getConfigLocations()方法指定的配置文件中帮你自动注入
下面的例子就是通过setter方法来获得context里的ProductManager bean:
public class MyTest extends AbstractDependencyInjectionSpringContextTests {
ProductManager productManager;
public String[] getConfigLocations() {
String[] configLocations = { "file:WebContent/WEB-INF/applicationContext.xml" };
return configLocations;
}
public void testGetProduct() {
assertEquals("tomson",productManager.getProductByName("tomson").getName());
}
//通过setter方法自动从context里注入productManager bean,而不用显示调用applicationContext.getBean(XXX)
public void setProductManager(ProductManager productManager) {
this.productManager = productManager;
}
}
但是如 果context里有多个bean都定义为一个类型(例如有多个bean都是ProductManager class类型的),那么对这些bean就无法通过setter方法来自动依赖注入(因为有多个bean同一个类型,不知要自动注入哪个)。在这种情况下 你需要显示的调用applicationContext.getBean(XXX)来注入。如:
public class MyTest extends AbstractDependencyInjectionSpringContextTests {
ProductManager productManager;
public String[] getConfigLocations() {
String[] configLocations = { "file:WebContent/WEB-INF/applicationContext.xml" };
return configLocations;
}
public void onSetUp() {
productManager = (ProductManager) applicationContext.getBean("productManager");
}
public void testGetProduct() {
assertEquals("tomson",productManager.getProductByName("tomson").getName());
}
}
如果你的TestCase不使用依赖注入,只要不定义任何setters方法即可。或者你可以继承 AbstractSpringContextTests --这个 org.springframework.test 包中的根类,而不是继承AbstractDependencyInjectionSpringContextTests(及其子类)。这是因为AbstractSpringContextTests 只包括用来加载Spring Context的便利方法但没有自动依赖注入的功能。
本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/chinping_tung/archive/2009/01/19/3837257.aspx