Reputation: 8986
I have a class that uses a method from a bean.
I'm trying to inject that method into my class using @Autowired
, but it gives me 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);
}
}
My 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>
Why is this field not being filled? Am I missing something?
Upvotes: 2
Views: 2114
Reputation: 42849
Since ChangePasswordServiceImpl
is not a Spring managed class (it is not in the xml configuration, therefore it is not a part of the ApplicationContext
) @Autowired
will do nothing for your class, which will cause you to get a NullPointerException
when you try to use an instance of the class.
You should define a bean for ChangePasswordServiceImpl
in your xml configuration, along with the rest that are currently there.
<bean id="changePasswordService" class="the.package.ChangePasswordServiceImpl"/>
Finally, you can then get a hold of it via the ApplicationContext
.
//assuming you are holding onto an instance of the ApplicationContext
ChangePasswordServiceImpl service = appContext.getBean("changePasswordService", ChangePasswordServiceImpl.class);
service.changePassword("old", "new");
Upvotes: 2