spring - 没有为每个用户创建 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。即使我也将范围指定为原型,它的行为仍然像单例。
解决方案
AuditorAware
应该是单例。您应该在每次AuditAware.getCurrentAuditor
调用时检索当前用户。不止一次。
将您的代码重写为这样的内容。
@Bean
public AuditorAware<String> auditorAware() {
return () -> getCurrentAuthentication().map(Authentication::getName());
}
private Optional<Authentication> getCurrentAuthentication() {
return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication());
}
推荐阅读
- c# - 为集成测试播种 WebApplicationFactory 不保存并给出 404
- python-3.x - 如何将这种类型的“字典”转换为数据框?
- java - selenium 根据索引位置获取 li 元素并单击复选框
- html - 引导显示无法在手机上进行生产
- java - Java Cucumber 自定义对象类型参数
- javascript - 通过正则表达式 WordPress 修改菜单项的第一个字母不起作用
- android - 外部图像未在 Android 中显示
- java - Java string.split 与 C# Regex.split - 限制为一定数量的字段
- python - Dask 数据框的值
- javascript - Raspberry Pi Zero W 上的 Node.js,依赖项不会自动下载