在服务中访问请求范围的Bean

时间:2018-07-18 09:22:50

标签: spring spring-mvc spring-boot spring-bean

我有一个常规bean,可以通过过滤器/拦截器将其放置在@Scope("request")中,或者(a)HttpServletRequest或。

如何在@Service中访问这种bean,这是一种应用程序范围内的单例?

之所以这样,是因为我有一个带有一些请求元数据的自定义对象RequestContext(主要来自自定义httpHeaders的信息)。众所周知,我将此对象作为参数传递给每个服务的每个方法,这是很多样板代码。

1 个答案:

答案 0 :(得分:3)

只要将bean声明为请求范围,Spring就会处理其余部分。

@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public RequestContext requestContext() {
    return new RequestContext();
}

以通常的方式访问bean,只需对其自动接线即可。

@Autowired
private RequestContext requestContext;

Service Bean将是一个sigleton,但在线程的基础上将RequestContext Bean附加到线程中,因此每次调用方法时,您将获得一个不同的实例。

请注意,您必须拥有一个Web上下文,即运行一个Web服务器/ Web应用程序