【问题标题】:How to inject request scoped bean?如何注入请求范围的bean?
【发布时间】:2017-04-17 02:49:26
【问题描述】:

我想将我的请求范围 bean 注入我的另一个 bean。

@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST)
public class UiCtx {

    @Autowired(required = true)
    private ApplicationContext ctx;

    @Autowired(required = true)
    private ServletWebRequest req;

    // [...]
}

我尝试将此 bean 注入 JPage bean:

@Component
@Scope("prototype")
public class Jpage extends AbstractUiComponent {
   // [...]
}

public abstract class AbstractUiComponent  {

    @Autowired(required = true)
    private UiCtx ctx;
    // [...]
}

在我尝试过的控制器中:

@RestController
class GreetingController {

    @RequestMapping("/jpage")
    void jpage(HttpServletRequest request, HttpServletResponse response,
            @Autowired @Qualifier("jpage") AbstractUiComponent jpage) throws IOException {
        WritePage.writeWebPage(request, response, jpage);
       }
    }
}

我明白了:

无法实例化 [pl.mirage.components.AbstractUiComponent]: 它是一个抽象类吗?嵌套异常是 java.lang.InstantiationException

又一次尝试。它不起作用,因为 @RestController 是单例 - 您不能将请求范围注入单例范围:

@RestController
class GreetingController {

    @Autowired
    @Qualifier("jpage")
    AbstractUiComponent jpage;

    @RequestMapping("/jpage")
    void jpage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        WritePage.writeWebPage(request, response, jpage);
    }
}

我明白了:

org.springframework.beans.factory.UnsatisfiedDependencyException: 创建名为“greetingController”的 bean 时出错:不满意 通过字段“jpage”表示的依赖关系;嵌套异常是 org.springframework.beans.factory.UnsatisfiedDependencyException: 创建名为“jpage”的 bean 时出错:不满足的依赖关系 通过字段“ctx”表示;嵌套异常是 org.springframework.beans.factory.BeanCreationException:错误 创建名为 'uiCtx' 的 bean:范围 'request' 对 当前线程;如果你考虑为这个 bean 定义一个作用域代理 打算从单例中引用它;嵌套异常是 java.lang.IllegalStateException:未找到线程绑定请求:是 您指的是实际 Web 请求之外的请求属性, 或处理原始接收线程之外的请求?如果 你实际上是在一个网络请求中操作并且仍然收到这个 消息,您的代码可能在 DispatcherServlet/DispatcherPortlet:在这种情况下,使用 RequestContextListener 或 RequestContextFilter 暴露当前 请求。

可以通过将UICtxJPage 注释为@Scope(value = "[..]", proxyMode = ScopedProxyMode.TARGET_CLASS) 来解决此问题。

仅当JPage 作为控制器字段注入时才有效。 JPage 作为方法参数注入时不起作用。

我应该如何注入请求范围的 bean?

【问题讨论】:

标签: spring-boot spring-mvc dependency-injection requestscope


【解决方案1】:

遵循错误消息中给出的建议(我以粗体强调):

BeanCreationException:创建名为 'uiCtx' 的 bean 时出错:范围 'request' 对于当前线程无效; 如果您打算从单例中引用此 bean,请考虑为该 bean 定义一个作用域代理

您需要 proxyMode 来启动应用程序并注入 UICtx 依赖项,例如定义

@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class UiCtx {
   // omitted class body
}

或简写@RequestScope。见Baeldung TutorialTom's comment中的重复链接:

Inject request scoped bean into another bean

【讨论】:

    猜你喜欢
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 2015-02-23
    相关资源
    最近更新 更多