我有一个 spring mvc 应用程序,它大量使用定义在 请求范围。现在我必须在这个范围之外使用这个应用程序的一部分(在 Magnolia CMS 中的 qwertz 作业)。这当然行不通:
Error creating bean with name 'requestHelper': Scope 'request' is not active for the current thread
我无法更改 bean 的范围,也无法更改代码。所以我唯一的可能 似乎将当前线程的范围更改为请求范围模型。
我试过类似的东西
XmlWebApplicationContext context = (XmlWebApplicationContext) ApplicationContextProvider.getApplicationContext() ;
MockServletContext mockServletContext = new MockServletContext("/");
context.setServletContext(mockServletContext);
context.refresh();
但这仍然没有激活当前线程中的请求范围。我怎样才能实现 这个?
最佳答案
可以按如下方式激活请求范围:
RequestContextHolder.setRequestAttributes(
new ServletRequestAttributes(new MockHttpServletRequest()));
...
((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.requestCompleted();
RequestContextHolder.resetRequestAttributes();
虽然我认为在生产代码中使用这样的 hack 并不是一个好主意。
https://stackoverflow.com/questions/10244431/