编程语言
首页 > 编程语言> > java-如何在异步任务中利用spring-data-jpa审核(AuditorAware)?

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

作者:互联网

当前,我的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(…)异步返回,由于getAuthentication()为空,AuditorAwareImpl.getCurrentAuditor()方法将引发NullPointerException:

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

到目前为止,我已经将调用请求的用户作为Job的非识别参数包括在内,但不知道从何处着手.

当SecurityContextHolder不适合查找调用“审计员”时,建议的利用spring的内置审计的方法是什么?

解决方法:

您可以将AsyncTaskExecutor包装在DelegatingSecurityContextAsyncTaskExecutor中,该DelegatingSecurityContextAsyncTaskExecutor是专门为传播Spring SecurityContext设计的.另外,您还需要为安全上下文设置MODE_INHERITABLETHREADLOCAL.

标签:spring-data,java
来源: https://codeday.me/bug/20191111/2018635.html