Spring @Autowired为null

时间:2015-01-18 17:34:17

标签: java spring

我有@ComponentA,其中AutoWires包含类A的简单配置的类。我已经为配置文件创建了一个bin。但由于某种原因,它是空的。你能帮我解决一下这个问题吗?

@Component
public class SearchEngineDriver {

    @Autowired(required = true)
    private EngineContext context;


    public SearchEngineDriver(){
         String clusterName = context.getClusterName();
    }
}


public class EngineContext {

    private String clusterName;

    public EngineContext(String clusterName){
        this.clusterName = clusterName;
    }

    public String getClusterName(){
        return this.clusterName;
    }
}

第3课。

    @Autowired
    private SearchEngineDriver searchEngineDriver;

MVC-调度-servlet.xml中

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       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="org.electronsoftware" />
    <mvc:annotation-driven/>
    <mvc:resources mapping="/resources/**" location="/resources/" />

    <import resource="classpath*:/application-context.xml"/>

    <bean
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

</beans>

应用context.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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd">


    <context:property-placeholder location="classpath:application.properties"/>


    <bean id="searchEngineContext" class="org.electronsoftware.KGB.search.context.EngineContext" >
        <constructor-arg value="${kgb.search.engine.clustername}"/>
    </bean>

</beans>

1 个答案:

答案 0 :(得分:6)

您正在从构造函数访问自动连接字段。在构造函数运行时,Spring还没有机会初始化该字段。而是使用@PostConstruct方法来执行取决于自动装配值的逻辑。