SpringBoot SimpleThreadScope不会将存储的对象从Filter保存到RestController

时间:2018-01-06 04:35:24

标签: spring filter controller threadscope

我必须得到请求语言Http Header并将其存储在rip + Lsomething的线程上下文中,Service可以使用RestController来获取它们。但我发现,SimpleThreadScope无法获取存储的对象,我将创建一个新实例。我检查过,从@RestController@RestController即可。但是无法通过@service安装的线程范围的bean将对象从Filter传输到@RestController

为什么SimpleThreadScope实施的范围无法从过滤器(SimpleThreadScope)转移到控制器(GenericFilterBean)。

1 个答案:

答案 0 :(得分:2)

如果您需要能够从过滤器更新bean的状态,之后能够读取@RestController@Service中的值并使用SimpleThreadScope然后< / p>

  1. 您需要注册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());
            }
        };
    }
    
  2. 你应该用@Scope注释你的bean(&#34; thread&#34;)

    @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());
    
  3. 在过滤器中注入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);
        }
    }
    
  4. 这是一篇有用的文章,描述了春天的范围:http://www.baeldung.com/spring-bean-scopes。你可以在那里找到有关proxyMode的详细信息。

    您可以看到@RequestScope可能对您有用。

    也许拦截器可以为你的任务工作。请参阅本文中的示例http://www.baeldung.com/spring-http-logging