小编Tra*_*hoa的帖子

如何在Spring Boot中的每个请求中获取当前用户?

我想在每个请求中获取用户的用户名,以将其添加到日志文件中。

这是我的解决方案:

首先,我创建了一个LoggedUser具有static属性的:

public class LoggedUser {

    private static final ThreadLocal<String> userHolder = 
        new ThreadLocal<>();

    public static void logIn(String user) {
        userHolder.set(user);
    }

    public static void logOut() {
        userHolder.remove();
    }

    public static String get() {
        return userHolder.get();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我创建了一个支持类来获取用户名:

public interface AuthenticationFacade {
    Authentication getAuthentication();
}
Run Code Online (Sandbox Code Playgroud)
@Component
public class AuthenticationFacadeImpl implements AuthenticationFacade {
    @Override
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,我在我的控制器中使用了它们:

    @RestController
    public class ResourceController {

        Logger logger = LoggerFactory.getLogger(ResourceController.class);

        @Autowired
        private GenericService …
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc spring-boot

4
推荐指数
1
解决办法
2万
查看次数

标签 统计

java ×1

spring ×1

spring-boot ×1

spring-mvc ×1