我在@Autowired注释中遇到问题
autoWiredLocallyTest()传递
autoWireAtClassTest()失败
以下是我的测试用例:
/**
* Spring Autowired test.
*/
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class AutowiredTest {
@Autowired
private ActionBeans localBeans;
@Test
public void autoWiredLocallyTest(){
//pre-test
Assert.assertNotNull(localBeans);
}
@Test
public void autoWireAtClassTest(){
TestClazz t = new TestClazz();
boolean isAutoWiredFromClass = t.isAutowired();
Assert.assertTrue(isAutoWiredFromClass);
}
}
TestClazz是:
public class TestClazz {
@Autowired
@Qualifier("actions")
private ActionBeans tempowieBiny;
public boolean isAutowired(){
return(this.tempowieBiny!=null);
}
}
的applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="actions.xml" />
<import resource="datasources.xml" />
</beans>
actions.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id='actions' class="net.virtalab.jsonio.configuration.actions.ActionBeans" scope="singleton">
<qualifier value="actions" />
</bean>
</beans>
错误或未完成,但需要做什么?
我使用Spring 3.2.5-RELEASE。
答案 0 :(得分:1)
您正在使用新运算符(TestClazz
)实例化TestClazz t = new TestClazz();
。如果希望正确初始化@autowired bean,则需要从spring上下文加载它。
尝试:
@Autowired
ApplicationContext testContext;
@Test
public void autoWireAtClassTest(){
// TestClazz t = new TestClazz();
TestClazz t = (TestClazz)testContext.getBean(TestClazz.class);
boolean isAutoWiredFromClass = t.isAutowired();
Assert.assertTrue(isAutoWiredFromClass);
}
答案 1 :(得分:0)
这里的问题是你每次都在创建新的TestClazz对象。自动换行:
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class AutowiredTest {
@Autowired
private ActionBeans localBeans;
// Added here
@Autowired
private TestClazz t;
@Test
public void autoWiredLocallyTest(){
//pre-test
Assert.assertNotNull(localBeans);
}
@Test
public void autoWireAtClassTest(){
//TestClazz t = new TestClazz(); COMMENTED OUT
boolean isAutoWiredFromClass = t.isAutowired();
Assert.assertTrue(isAutoWiredFromClass);
}
}