在spring中获取Autowired对象的null值

时间:2016-09-22 09:14:18

标签: spring

我有以下bean XML,它在ApplicationConfiguration.java中导入,刚创建了在Test类中自动装配的DbManager,但它始终为null。 任何人都可以提供帮助。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-4.0.xsd
           http://www.springframework.org/schema/cache 
                    http://www.springframework.org/schema/cache/spring-cache.xsd">

    <bean id="dbManager" class="com.bandu.myfriendsbook.common.services.dbservices.dbmanager.impl.DbManagerImpl">

    </bean>

    <bean id="dbManagers"  class="java.util.ArrayList">
        <constructor-arg>
            <list>
                <ref bean="dbManager"/>
            </list>
        </constructor-arg>
    </bean>

</beans>   

和配置java文件

@Configuration("applicationConfiguration")
@EnableSpringConfigured
@ComponentScan
@EnableCaching(mode = AdviceMode.PROXY, proxyTargetClass = true)
@EnableTransactionManagement(proxyTargetClass = true, mode = AdviceMode.PROXY)
@ImportResource({"classpath:META-INF/app-spring-common-config.xml"})
public class ApplicationConfiguration extends CachingConfigurerSupport{

        //othere beans like datasource, cachemanager
}

现在只需在ApplicationTest.java中调用bean,但它始终为null。

@Component
public class ApplicationTest {

    @Autowired
    private DbManagerImpl dbManager;

    public Integer testQuery(){
        return dbManager.testQuery();
    }
}

2 个答案:

答案 0 :(得分:2)

您必须将@ComponentScan与参数basePackages或basePackagesClasses一起使用。 例如:

 @ComponentScan(basePackages = {"com.example"})

答案 1 :(得分:0)

<context:annotation-config/>添加到ur xml文件以使用@Autowired注释。