Access a request scoped Bean in Service

扶醉桌前 提交于 2019-11-30 20:32:21

问题


I have a regular bean, which is either (a) @Scope("request") or (b) placed in a HttpServletRequest via Filter/ Interceptor.

How to access this beans in a @Service which is kind of an application scoped singleton?

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.


回答1:


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();
}

Access the bean in the usual way, just autowire it.

@Autowired
private RequestContext requestContext;

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.

NOTE YOU MUST HAVE A WEB CONTEXT, i.e. RUNNING A WEB SERVER/WEB APP



来源:https://stackoverflow.com/questions/51398260/access-a-request-scoped-bean-in-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!