如果您需要能够从过滤器更新 bean 的状态,然后能够读取@RestController
or中的值,然后@Service
使用SimpleThreadScope
你需要注册 SimpleThreadScope
@Bean
public static BeanFactoryPostProcessor beanFactoryPostProcessor() {
return new BeanFactoryPostProcessor() {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
logger.info("postprocessor");
beanFactory.registerScope("thread", new SimpleThreadScope());
}
};
}
你应该用 @Scope("thread") 注释你的 bean
@Component
@Scope(scopeName = "thread", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyBean {
@RestController
public class SampleController {
private static final Logger logger = LoggerFactory.getLogger(SampleController.class);
@Autowired
private MyBean myBean;
@GetMapping("/test/{somePathVar}")
public String test(@PathVariable String somePathVar) throws InterruptedException, ExecutionException {
logger.info("looking for bean data: {}", myBean.getData());
在过滤器中注入 bean 并更新它的状态
@Component
public class MyFilter extends GenericFilterBean {
private static final Logger logger = LoggerFactory.getLogger(MyFilter.class);
@Autowired
private MyBean myBean;
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
myBean.setData(servletRequest.getParameter("test"));
filterChain.doFilter(servletRequest, servletResponse);
}
}
这是一篇描述春季作用域的有用文章:http ://www.baeldung.com/spring-bean-scopes 。您可以在此处找到有关 proxyMode 的详细信息。
您可以看到这@RequestScope
可能对您有用。
也可能拦截器会为你的任务工作。请参阅本文中的示例http://www.baeldung.com/spring-http-logging