首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从AuthenticationSuccessHandler获取映射器

问从AuthenticationSuccessHandler获取映射器
EN

Stack Overflow用户
提问于 2016-02-03 21:05:18
回答 1查看 114关注 0票数 0

我正在尝试在Spring应用程序成功登录后返回一些用户数据。为此,我需要使用已经通过工厂在引导程序上设置的Jackson映射器序列化我的主体。

是否有方法将其注入身份验证处理程序?

代码语言:javascript
复制
@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();*/
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-04 02:14:43

tl;dr;

与其使用Factory,不如让ObjectMapper成为Spring。这样,就可以将其注入Spring和泽西组件中。

代码语言:javascript
复制
@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来获取

代码语言:javascript
复制
ServiceLocator l = ...
AuthenticationSuccessHandler handler = l.getService(AuthenticationSuccessHandler.class);

那应该管用。如果您通过一个ObjectMapper绑定了一个HK2 Factory,并且要将映射器@Inject到AuthenticationSuccessHandler中,那么当通过ServiceLocator检索时,它将被注入。

尽管如此,Security并不通过HK2,所以它从来没有机会通过HK2获得ObjectMapper。但是,如果将映射器注册为Spring,那么Spring可以将其注入AuthenticationSuccessHandler。而且映射器仍然可以通过HK2 ServiceLocator (因为有弹簧桥)使用,所以您仍然可以在泽西使用它,就像它与Factory绑定一样。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35187664

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档