没有为每个用户创建 JPA AuditorAware
JPA AuditorAware not getting created for each user
我已经使用 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。即使我也将范围指定为原型,它仍然表现得像单例。
AuditorAware
应该是单例。每次调用 AuditAware.getCurrentAuditor
时,您应该检索当前用户。不止一次。
将你的代码重写成这样。
@Bean
public AuditorAware<String> auditorAware() {
return () -> getCurrentAuthentication().map(Authentication::getName());
}
private Optional<Authentication> getCurrentAuthentication() {
return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication());
}
我已经使用 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。即使我也将范围指定为原型,它仍然表现得像单例。
AuditorAware
应该是单例。每次调用 AuditAware.getCurrentAuditor
时,您应该检索当前用户。不止一次。
将你的代码重写成这样。
@Bean
public AuditorAware<String> auditorAware() {
return () -> getCurrentAuthentication().map(Authentication::getName());
}
private Optional<Authentication> getCurrentAuthentication() {
return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication());
}