kal*_*mar 1 spring spring-mvc spring-bean spring-boot
我有一个普通 bean,它是 (a)@Scope("request")或 (b) 放置在一个HttpServletRequestvia 过滤器/拦截器中。
如何在@Service一种应用程序范围的单例中访问这个 bean ?
这样做的原因是,因为我有一个RequestContext带有一些请求元数据的自定义对象(主要是来自自定义 httpHeaders 的信息)。要知道,我将此对象作为参数传递给每个服务的每个方法,这是很多样板代码。
只要 bean 被声明为请求范围,Spring 就会处理剩下的事情。
@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public RequestContext requestContext() {
return new RequestContext();
}
Run Code Online (Sandbox Code Playgroud)
以通常的方式访问 bean,只需自动装配它。
@Autowired
private RequestContext requestContext;
Run Code Online (Sandbox Code Playgroud)
服务 bean 将是一个单例,但在幕后,RequestContext bean 附加到线程,因此每次调用方法时您将获得不同的实例。
注意你必须有一个网络上下文,即运行一个网络服务器/网络应用程序
| 归档时间: |
|
| 查看次数: |
5147 次 |
| 最近记录: |