我正在尝试在Spring应用程序成功登录后返回一些用户数据。为此,我需要使用已经通过工厂在引导程序上设置的Jackson映射器序列化我的主体。
是否有方法将其注入身份验证处理程序?
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_OK);
UserDetails me = (UserDetails) authentication.getPrincipal();
PrintWriter writer = response.getWriter();
/*mapper.writeValue(writer, user); <- how to get the mapper?
writer.flush();*/
}发布于 2016-02-04 02:14:43
tl;dr;
与其使用Factory,不如让ObjectMapper成为Spring。这样,就可以将其注入Spring和泽西组件中。
@Bean
public ObjectMapper mapper() {
ObjectMapper mapper = new ObjectMapper();
return mapper;
}当您使用HK2 (泽西的DI框架) Factory创建ObjectMapper时,注入只对通过HK2 ServiceLocator检索的组件可用,HK2 ServiceLocator是SpringApplicationContext的HK2模拟。
当您在泽西使用Spring时,这两者是如何在幕后交互的,是通过HK2 弹簧桥实现的。例如,假设AuthenticationSuccessHandler在ApplicationContext中注册。配置了弹簧桥之后,我们还可以通过AuthenticationSuccessHandler通过ServiceLocator来获取
ServiceLocator l = ...
AuthenticationSuccessHandler handler = l.getService(AuthenticationSuccessHandler.class);那应该管用。如果您通过一个ObjectMapper绑定了一个HK2 Factory,并且要将映射器@Inject到AuthenticationSuccessHandler中,那么当通过ServiceLocator检索时,它将被注入。
尽管如此,Security并不通过HK2,所以它从来没有机会通过HK2获得ObjectMapper。但是,如果将映射器注册为Spring,那么Spring可以将其注入AuthenticationSuccessHandler。而且映射器仍然可以通过HK2 ServiceLocator (因为有弹簧桥)使用,所以您仍然可以在泽西使用它,就像它与Factory绑定一样。
https://stackoverflow.com/questions/35187664
复制相似问题