如何在实现Spring数据JPA AuditorAware接口时获取getUserPrincipal().getUserName()

如何在实现Spring数据JPA AuditorAware接口时获取getUserPrincipal().getUserName(),spring,authentication,spring-data,spring-data-jpa,jetspeed2,Spring,Authentication,Spring Data,Spring Data Jpa,Jetspeed2,我试图在我当前的项目中使用SpringDataJPA(1.6.2)。看起来一切都很好,但我在实现AuditorAware接口时遇到了问题 我的应用程序将部署到一个旧的Apache Jetspeed JSR168兼容门户。此门户负责用户身份验证/授权。因此,我不必使用像Spring security或Shiro这样的安全框架。我的应用程序中的其他框架包括: Struts 1.2.4(带Struts入口桥) 春季3.2.10 JPA(作为ORM提供程序的Hibernate 3.6.10) 我想在我的

我试图在我当前的项目中使用SpringDataJPA(1.6.2)。看起来一切都很好,但我在实现AuditorAware接口时遇到了问题

我的应用程序将部署到一个旧的Apache Jetspeed JSR168兼容门户。此门户负责用户身份验证/授权。因此,我不必使用像Spring security或Shiro这样的安全框架。我的应用程序中的其他框架包括:

  • Struts 1.2.4(带Struts入口桥)
  • 春季3.2.10
  • JPA(作为ORM提供程序的Hibernate 3.6.10)
  • 我想在我的实体中使用@CreatedBy和@LastModifiedBy注释字段(我让@CreatedDate和@LastModifiedDate工作)。在我的应用程序中,我通常使用request.getUserPrincipal().getUserName()获取用户名

    但是,在实现AuditorAware接口时,如何获得用户名呢

    来自以下方面的示例实现:

    类SpringSecurityAuditorAware实现AuditorAware{
    公共用户getCurrentAuditor(){
    身份验证=SecurityContextHolder.getContext().getAuthentication();
    if(authentication==null | |!authentication.isAuthenticated()){
    返回null;
    }
    返回((MyUserDetails)authentication.getPrincipal()).getUser();
    }
    }
    
    不知何故,我想实现如下AuditorAware:

    class MyAuditorAware implements AuditorAware<String> {
        public String getCurrentAuditor() {
            return <<principal from servlet- or portletcontext>>.getUserName();
        }
    }
    
    MyAuditorAware类实现AuditorAware{ 公共字符串getCurrentAuditor(){ return.getUserName(); } }
    如何在不添加额外框架的情况下实现这一点?

    正如Konstantin在其评论中提到的,您可能希望将主体名称保存在适合请求的范围内。这很可能是一个
    ThreadLocal
    。这使您可以在以后的
    AuditorAware
    实现中轻松获得它


    要继续使用Spring的命名,请调用它
    PrincipalContextHolder
    。作为一个起点,您可以查看的源代码是一个
    ContextHolder

    的简单实现,这里有一个肮脏的把戏——在您的auditoraware中的servlet/portlet请求处理ant稍后调用holder getter一开始就在某种静态holder类中捕获您的用户主体
    class MyAuditorAware implements AuditorAware<String> {
        public String getCurrentAuditor() {
            return <<principal from servlet- or portletcontext>>.getUserName();
        }
    }