如何在异步任务中利用spring-data-jpa审计(AuditorAware)?

时间:2017-06-16 04:03:01

标签: java spring-data

目前,我的AuditorAware实施使用Spring的SecurityContextHolder来检索当前的Auditor以保存创建/修改用户名:

@Service
public class AuditorAwareImpl implements AuditorAware<UserDetails> {

    private final UserDetailsService userDetailsService;

    @Autowired
    public AuditorAwareImpl(UserDetailsService userDetailsService){
        this.userDetailsService = userDetailsService;
    }

    @Override
    public UserDetails getCurrentAuditor() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return userDetailsService.loadUserByUsername(authentication.getName());
    }
}

除了Spring批处理SimpleAsyncTaskExecutor执行的异步任务外,大多数操作都适用。

当实体需要保存时,由于在处理请求后擦除了SecurityContextHolder,并且jobLauncher.run(...)异步返回,AuditorAwareImpl.getCurrentAuditor()方法会抛出NullPointerException由于空getAuthentication()

java.lang.NullPointerException: null
    at com.example.services.AuditorAwareImpl.getCurrentAuditor(AuditorAwareImpl.java:31)
    at com.example.services.AuditorAwareImpl.getCurrentAuditor(AuditorAwareImpl.java:18)

到目前为止,我已将请求调用用户作为非标识参数包含在作业中,但不知道从何处开始。

SecurityContextHolder不适合找到调用&#34;审核员&#34; 时,建议采用spring内置审核的方法

1 个答案:

答案 0 :(得分:3)

您可以将AsyncTaskExecutor包裹在专为传播Spring SecurityContext而设计的DelegatingSecurityContextAsyncTaskExecutor中。此外,您还需要为安全上下文设置MODE_INHERITABLETHREADLOCAL