春天的@Autowired不会注入依赖性



我有一个由各种模块组成的项目。基本上,我使用过Spring MVC;JUnit 4,一切都运行良好。但是现在,我添加了一些与测试或MVC无关的类,并且@Autowired注释不会向它们注入对象。同样的对象被注入到MVC和JUnit类中,所以我真的很困惑。

这是Spring上下文XML:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 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-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    <context:component-scan base-package="com.justic.more" />
    <mvc:annotation-driven />
    <context:annotation-config />
    <bean id="monkDAO" class="com.justic.more.data.monkDAO" />
    <bean id="BidDAO" class="com.justic.more.data.BidDAO" />
</beans>

我想注入的类:

@Component
Public Class Tesser {
@Autowired
MonkDAO monkdao;
...
blablabla
...
}

从与OP的聊天中可以清楚地看出,他创建了像Tesser tesser = new Tesser()这样的对象,而不是将其注入测试类。Spring没有机会在bean中自动装配非它自己创建的依赖项。

解决方案是将Tesser对象自动连接到测试类中,以便Spring可以注入依赖项。

@Autowired
private Tesser tesser;
@Test
public void testSth() {
    assertTrue(tesser.someBoolReturningMethodUtilizingMonkDAO());
}

添加限定符:

@Resource(name = "monkDAO")

最新更新