gpt4 book ai didi

java - @Autowired 在类里面

转载 作者:行者123 更新时间:2023-12-01 13:45:59 25 4
gpt4 key购买 nike

我在使用 @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。

最佳答案

您正在使用 new 运算符 (TestClazz t = new TestClazz();) 实例化 TestClazz。如果您希望正确初始化 @autowired beans,您需要从 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);
}

关于java - @Autowired 在类里面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20376121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com