Autowired поле дает мне нулевое исключение - PullRequest
2 голосов
/ 21 декабря 2011

У меня есть класс, который использует метод из 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 file:

<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 Ответ

2 голосов
/ 21 декабря 2011

Поскольку ChangePasswordServiceImpl не является классом, управляемым Spring (его нет в конфигурации xml, поэтому он не является частью ApplicationContext) @Autowired ничего не изменит для вашего класса, что приведет к тому, что вы получитеNullPointerException когда вы пытаетесь использовать экземпляр класса.

Вы должны определить bean-компонент для ChangePasswordServiceImpl в вашей конфигурации xml вместе с остальными, которые в данный момент существуют.

<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");
...