Autowired字段给出了null异常

时间:2011-12-21 00:58:04

标签: spring dependency-injection inversion-of-control

我有一个使用bean中的方法的类。

我正在尝试使用@Autowired将该方法注入我的班级,但它给了我NullPointerException。

public class ChangePasswordServiceImpl extends RemoteServiceServlet implements
        ChangePasswordService {

    @Autowired
    @Qualifier("userDetailsManager")
    private JdbcUserDetailsManager userDetailsManager;

    @Override
    public void changePassword(String oldPassword, String newPassword) {

        // This is the line that throws NullPointerException, i.e., userDetails
        // Manager is not being injected by Spring
        userDetailsManager.changePassword(oldPassword, newPassword);

    }

}

我的 xml 文件:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    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.1.xsd
             http://www.springframework.org/schema/jdbc
             http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
             http://www.springframework.org/schema/context
             http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:annotation-config/>

    <bean id="securityDataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">

        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url"
            value="jdbc:mysql://localhost:3306/login" />
        <property name="username" value="root" />
        <property name="password" value="password" />
    </bean>

    <bean id="userDetailsManager"
        class="org.springframework.security.provisioning.JdbcUserDetailsManager">
        <property name="dataSource" ref="securityDataSource" />
        <property name="authenticationManager" ref="authenticationManager" />
        <qualifier value="userDetailsManager"/>
    </bean>

</beans>

为什么这个字段没有填写?我错过了什么吗?

1 个答案:

答案 0 :(得分:2)

由于ChangePasswordServiceImpl不是Spring托管类(它不在xml配置中,因此它不是ApplicationContext的一部分)@Autowired对您的类不执行任何操作,当您尝试使用该类的实例时,这将导致您获得NullPointerException

您应该在xml配置中为ChangePasswordServiceImpl定义一个bean,以及当前存在的其余bean。

<bean id="changePasswordService" class="the.package.ChangePasswordServiceImpl"/>

最后,您可以通过ApplicationContext获取它。

//assuming you are holding onto an instance of the ApplicationContext
ChangePasswordServiceImpl service = appContext.getBean("changePasswordService", ChangePasswordServiceImpl.class);
service.changePassword("old", "new");