gpt4 book ai didi

spring - 在实际 Web 请求之外使用请求范围的 bean

转载 作者:IT老高 更新时间:2023-10-28 13:49:59 28 4
gpt4 key购买 nike

我有一个 Web 应用程序,它在一个单独的线程中运行了一个 Spring Integration 逻辑。问题是在某些时候我的 Spring Integration 逻辑尝试使用请求范围的 bean,然后我得到以下错误:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.tenantContext': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.


Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

我设置了 ContextLoaderListener:

<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

我的 Scoped Bean 是这样注释的(因为我听说代理我的 bean 会有所帮助):

@Component
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class TenantContext implements Serializable {

我正在做的事情可能吗?如果是,我在这里错过了什么?如果没有,关于我如何实现这一目标的任何其他建议?

最佳答案

对于 Spring 4 框架添加 servletContext.addListener(new RequestContextListener());

public class WebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { RootConfiguration.class };
}

@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebMvcConfiguration.class };
}

@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}

@Override
protected Filter[] getServletFilters() {
return new Filter[] { new HiddenHttpMethodFilter() };
}

**@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
servletContext.addListener(new RequestContextListener());
}**
}

关于spring - 在实际 Web 请求之外使用请求范围的 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17424739/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com