application.properties中配置${user.id}怎么设置值
时间: 2024-02-09 16:09:51 浏览: 68
可以通过在Spring Security中获取当前用户的ID,并将其存储在Spring的全局变量中,然后在application.properties中引用该变量来设置${user.id}的值。
以下是一个示例:
1. 创建一个Spring Security配置类:
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// ...
@Override
protected void configure(HttpSecurity http) throws Exception {
// ...
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// ...
}
@Bean
public RequestContextListener requestContextListener() {
return new RequestContextListener();
}
@Bean
public ServletContextInitializer servletContextInitializer() {
return servletContext -> servletContext.addListener(requestContextListener());
}
@Bean
public CurrentUserHandlerMethodArgumentResolver currentUserHandlerMethodArgumentResolver() {
return new CurrentUserHandlerMethodArgumentResolver();
}
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(currentUserHandlerMethodArgumentResolver());
}
}
```
2. 创建一个用于存储当前用户的全局变量:
```
public class CurrentUser {
private static final ThreadLocal<Long> threadLocal = new ThreadLocal<>();
public static void set(Long userId) {
threadLocal.set(userId);
}
public static Long get() {
return threadLocal.get();
}
public static void remove() {
threadLocal.remove();
}
}
```
3. 创建一个用于获取当前用户ID并将其存储在全局变量中的解析器:
```
public class CurrentUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterType().equals(Long.class) && parameter.hasParameterAnnotation(CurrentUserId.class);
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
return CurrentUser.get();
}
@EventListener
public void handleAuthenticationSuccessEvent(AuthenticationSuccessEvent event) {
CurrentUser.set(event.getUser().getId());
}
@EventListener
public void handleLogoutSuccessEvent(LogoutSuccessEvent event) {
CurrentUser.remove();
}
}
```
4. 在application.properties中引用${user.id}:
```
my.queue=user.queue.${currentUser}
```
这里使用了一个名为“currentUser”的变量,它的值是通过CurrentUserHandlerMethodArgumentResolver获取的当前用户ID。要使用该变量,也需要在MyMessageListener中添加一个参数:
```
@Component
public class MyMessageListener {
@RabbitListener(queues = "${my.queue}")
public void handleMessage(String message, @Value("${currentUser}") Long userId) {
System.out.println("Received message: " + message + " for user " + userId);
}
}
```
这样,你就可以通过${user.id}设置当前用户的队列名称,并在MyMessageListener中获取当前用户的ID。
阅读全文