在服务中访问请求范围的 Bean [英] Access a request scoped Bean in Service
问题描述
我有一个常规 bean,它是 (a) @Scope("request")
或 (b) 通过过滤器/拦截器放置在 HttpServletRequest
中.
I have a regular bean, which is either (a) @Scope("request")
or (b) placed in a HttpServletRequest
via Filter/ Interceptor.
如何在 @Service
中访问这个 bean,这是一种应用程序范围的单例?
How to access this beans in a @Service
which is kind of an application scoped singleton?
这样做的原因是,因为我有一个自定义对象 RequestContext
带有一些请求元数据(主要来自自定义 httpHeaders 的信息).要知道,我将这个对象作为参数传递给每个服务的每个方法,这是很多样板代码.
The reason for this is, because I have a custom object RequestContext
with some request metadata (mostly informations from custom httpHeaders). For know, i pass this object as parameter to each method on each service, which is a lot of boilerplate code.
推荐答案
只要将 bean 声明为请求作用域,其余的事情将由 Spring 来处理.
As long as the bean is declared as request scope, Spring will take care of the rest.
@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public RequestContext requestContext() {
return new RequestContext();
}
以通常的方式访问 bean,只需自动装配它.
Access the bean in the usual way, just autowire it.
@Autowired
private RequestContext requestContext;
服务 bean 将是一个单例,但在幕后,RequestContext bean 附加到线程,因此每次调用方法时您都会获得不同的实例.
The Service bean will be a sigleton but under the covers the RequestContext bean is attached to the thread so you will get a different instance each time a method is called.
注意你必须有一个网络上下文,即运行一个网络服务器/网络应用程序
这篇关于在服务中访问请求范围的 Bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!