简体   繁体   English

Spring 引导请求范围 Bean

[英]Spring Boot Request Scoped Bean

I am using spring boot for creating microservices.我正在使用 spring 引导来创建微服务。 I need to implement request scope beans as I get some information in header and need this to be available across all the classes for that particular request.我需要实现请求 scope bean,因为我在 header 中获得了一些信息,并且需要在该特定请求的所有类中都可以使用它。 Below is what I did, but I get null pointer error.下面是我所做的,但我得到 null 指针错误。

@Component
@RequestScope(proxyMode = ScopedProxyMode.TARGET_CLASS)
public Class RequestHeaderInfo {
   private String appInfo;
   ...
}

@Component
public class RequestFilter implements Filter {
    @Autowired
    private RequestHeaderInfo requestHeaderInfo;
  
    public void doFilter(ServletRequest req,....) {
        HTTPServletRequest request = (HTTPServletRequest) req;
        requestHeaderInfo.setAppInfo(request.getHeader("appInfo"))   //throws null pointer error here
        ....
    }
}  

@Contoller
public class RestController {

    @Autowired
    private RequestHeaderInfo requestHeaderInfo;
}

I want this request header info object to be available throughout the particular request.我希望此请求 header info object 在整个特定请求中可用。 In my filter class it throws null pointer error.在我的过滤器 class 中,它会引发 null 指针错误。 Am I on the right track implementing request scoped bean?我是否在正确的轨道上实施请求范围的 bean?

In our project (Spring boot multi-module and not microservices) we are using an Interceptor class to filter the request.在我们的项目(Spring boot 多模块而不是微服务)中,我们使用拦截器 class 来过滤请求。

@Component
public class RequestInterceptor implements org.springframework.web.servlet.HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        String appInfo = request.getHeader("appInfo");
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
        throws Exception {
    }
}

Plus our Bean with the request scope is configured like this加上我们请求 scope 的 Bean 配置如下

@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
@Component
public class RequestBean {

}

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM