Spring bean注入抛出空指针异常

时间:2014-09-03 18:11:52

标签: spring spring-mvc

我试图将beanB注入beanA,但出于某种原因,弹簧注射不起作用。当我尝试在beanB中使用beanA时,我得到空指针异常。

这是我的配置......

的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring/application-context.xml
        </param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

</web-app>

应用context.xml中

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans" .........>

    <import resource="dao-beans.xml"/>
    <import resource="service-beans.xml"/>
    ...................
    ...................
</beans>

服务-beans.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans".........>   

    <bean id="serviceBeanA" class="com.test.ServiceBeanAImpl"/>
    <bean id="serviceBeanB" class="com.my.kodak.ServiceBeanBImpl">
        <property name="serviceBeanA" ref="serviceBeanA"></property>
    </bean>
</beans>

ServiceBeanBImpl.java

public class ServiceBeanBImpl{

    private ServiceBeanAImpl serviceBeanA;

    private String a;

    private String b;

    public ServiceBeanBImpl(){
        initializeBeanB();
    }

    initializeBeanB(){
        a = serviceBeanA.getA(); /// this is the line that throws Null pointer exception
        b = serviceBeanA.getB();
    }

    public String getServiceBeanA(){
        return this.serviceBeanA;
    }

    public String setServiceBeanA(ServiceBeanAImpl serviceBeanA){
        this.serviceBeanA = serviceBeanA;
    }

}

当spring尝试初始化ServiceBeanBImpl时,它在调用serviceBeanA时失败。我在setServiceBeanA()方法上设置了一个调试点,它永远不会被调用。我也尝试过不同的参考策略,但没有一个能够起作用。

<bean id="serviceBeanB" class="com.my.kodak.ServiceBeanBImpl">
    <property name="serviceBeanA">
         <ref bean="serviceBeanA"/>
    </property>
</bean>

<bean id="serviceBeanB" class="com.my.kodak.ServiceBeanBImpl">
    <property name="serviceBeanA">
         <ref local="serviceBeanA"/>
    </property>
</bean>

1 个答案:

答案 0 :(得分:13)

Spring必须在执行其属性设置(setter注入)之前初始化对象。初始化意味着调用构造函数。所以Spring 第一次调用

public ServiceBeanBImpl(){
    initializeBeanB();
}

调用

initializeBeanB(){
    a = serviceBeanA.getA(); /// this is the line that throws Null pointer exception
    b = serviceBeanA.getB();
}

但是,财产注入尚未发生,serviceBeanA仍未初始化(null)。

考虑重构以使用构造函数注入

public ServiceBeanBImpl(ServiceBeanA serviceBeanA) {
    this.serviceBeanA = serviceBeanA;
    // initializeBeanB();
}

你也可以利用@PostConstruct并让Spring在所有注射完成后调用它。

@PostConstruct
void initializeBeanB() {
    ...
}