我想在每个请求中获取用户的用户名,以将其添加到日志文件中。
这是我的解决方案:
首先,我创建了一个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)