首页 > 解决方案 > 没有为每个用户创建 JPA AuditorAware

问题描述

我已经使用 JPA 审计实现了审计。我的代码如下所示:

@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorAware")
public class JpaConfiguration {

    @Bean
    @Scope(value= ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public AuditorAware<String> auditorAware() {
        final String currentUser;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(null != authentication) {
            currentUser = authentication.getName();
        } else {
            currentUser = null;
        }
        return () -> Optional.ofNullable(currentUser);
    }
}

我面临的问题是,如果我使用一个用户登录并执行一些操作,它工作正常。但是当我注销并使用另一个用户登录时,它仍然只使用最后一个用户。

调试代码后,我发现 spring 没有为每个用户创建 AuditorAware bean。它的行为就像单例 bean。即使我也将范围指定为原型,它的行为仍然像单例。

标签: springspring-bootjpaaudit

解决方案


AuditorAware应该是单例。您应该在每次AuditAware.getCurrentAuditor调用时检索当前用户。不止一次。

将您的代码重写为这样的内容。


@Bean
public AuditorAware<String> auditorAware() {
    return () -> getCurrentAuthentication().map(Authentication::getName());
}

private Optional<Authentication> getCurrentAuthentication() {
  return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication());
}

推荐阅读