【发布时间】:2015-09-12 01:41:05
【问题描述】:
我想在服务层获取当前用户
我尝试了以下代码,但出现空指针异常
@Service
public class MyService{
@Autowired
TodoRepository todoRepository;
public void execute(){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Todo todo = new Todo();
todo.setDomain(auth.getName());
todoRepository.save(todo);
}
谁能告诉我如何通过服务层中的spring security获取登录用户?
【问题讨论】:
-
从哪里得到空指针异常?理论上,如果您的设置有问题,它永远不应该为 null。
-
你总是从web层调用服务层吗? SecurityContext 基于线程范围(请求)工作。如果您启动一些异步方法,则会失败,因为它将是另一个线程。
标签: java spring spring-mvc spring-security