我有一个AuthenticationSuccessHandler,它应该持有UserService。我的问题是我在这行的userService上得到一个NullPointerException:
logger.debug(userService.getAllUsers().toString());
AuthenticationSuccessHandlerImpl:
@Repository
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
private static final Logger logger = LoggerFactory.getLogger(AuthenticationSuccessHandlerImpl.class);
@Autowired
private UserService userService;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
logger.debug(userService.getAllUsers().toString());
response.setStatus(HttpServletResponse.SC_OK);
response.sendRedirect("index");
}
}
我也尝试了@Service和@Component Annotation但是同样的错误。
它适用于我项目中的所有其他服务和控制器,但不适用于此Handler。
我的配置中也有这行代码:
<context:component-scan base-package="com.net4you.*" />
<tx:annotation-driven />
编辑: AuthenticationSuccessHandlerImpl不是使用new创建的,而是使用:
<security:form-login login-page="/login" default-target-url="/index" authentication-failure-url="/fail2login"
authentication-success-handler-ref="customAuthenticationSuccessHandler"/>
<beans:bean id="customAuthenticationSuccessHandler" class="com.net4you.slamanagement.helper.AuthenticationSuccessHandlerImpl"/>
答案 0 :(得分:4)
1)你不需要。*
<context:component-scan base-package="com.net4you.*" />
这就够了
<context:component-scan base-package="com.net4you" />
2)你确定userService是空的吗?
3)配置看起来很好,也许getAllUsers()方法返回null, 你能展示它的实现吗?
<强>更新强>
您可以通过两种方式解决此问题
1)删除
<beans:bean id="customAuthenticationSuccessHandler" class="com.net4you.slamanagement.helper.AuthenticationSuccessHandlerImpl"/>
并注释AuthenticationSuccessHandlerImpl,如下所示
@Component("customAuthenticationSuccessHandler")
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
private static final Logger logger = LoggerFactory.getLogger(AuthenticationSuccessHandlerImpl.class);
@Autowired
private UserService userService;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
logger.debug(userService.getAllUsers().toString());
response.setStatus(HttpServletResponse.SC_OK);
response.sendRedirect("index");
}
}
2)第二种方法是在AuthenticationSuccessHandlerImpl中创建用户服务的setter,手动在xml中创建userservice bean,然后使用xml中的authenticationSuccessHandlerImpl的setter属性直接注入它,这个解决方案比较复杂,我建议你先用一个
您的实现不起作用,因为您在xml中定义了bean而没有为其设置用户服务(如果您手动定义bean,则@autowired不起作用)然后您将此bean注入到form-login