【问题标题】:Spring Injection isn't working in Jersey Filter - @InjectParam Equivalent in jersey2Spring Injection 在 Jersey 过滤器中不起作用 - @InjectParam 在 jersey2 中等效
【发布时间】:2016-03-02 07:46:09
【问题描述】:

我正在尝试使用 spring 注入在 Je​​rsey-Filter 中注入一个对象。

如果我尝试 @Inject 方法,那么我会遇到异常

SEVERE: StandardWrapper.Throwable
MultiException stack 1 of 2
java.lang.IllegalStateException: Could not find an active context for org.jvnet.hk2.spring.bridge.api.SpringScope
        at org.jvnet.hk2.internal.ServiceLocatorImpl._resolveContext(ServiceLocatorImpl.java:2058)
        at org.jvnet.hk2.internal.ServiceLocatorImpl.access$000(ServiceLocatorImpl.java:120)
        at org.jvnet.hk2.internal.ServiceLocatorImpl$2.compute(ServiceLocatorImpl.java:186)
        at org.jvnet.hk2.internal.ServiceLocatorImpl$2.compute(ServiceLocatorImpl.java:182)

如果我尝试使用它在 Jersey 1.x 中定义的 @InjectParam,但是我使用的是 Jersey 2.17,其中找不到此注释。

知道如何在 jersey-filter 中执行此弹簧注射吗?

异常是什么意思?

Could not find an active context for org.jvnet.hk2.spring.bridge.api.SpringScope

【问题讨论】:

  • 在我看来,在初始化时,弹簧桥尚未正确初始化。我不确定在泽西岛是如何做到的,但你可以在这里看到更多关于 spring/hk2 桥的信息:hk2.java.net/2.5.0-b03/spring-bridge.html

标签: spring dependency-injection jersey-2.0


【解决方案1】:

更新编辑: 此外,您可以提供构造函数注入。 Jersey 的构造函数注入在过滤器而不是字段注入中为我工作

旧:

我通过在过滤器中注入 javax.servlet.ServletContext 并使用它通过 WebApplicationContextUtils

获取 beanIds 来实现这一点
public class LoginFilter implements ContainerRequestFilter {

    @Context private HttpServletRequest servletRequest;

    @Context private HttpServletResponse servletResponse;

    @Context private ServletContext servletContext;

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        try {

            WebApplicationContext springContext = 
                    WebApplicationContextUtils.getWebApplicationContext(servletContext);

            CookieAuthenticator     cookieAuthenticator = springContext.getBean(CookieAuthenticator.class);

            LoginInterceptorHelper  loginInterceptorHelper = springContext.getBean(LoginInterceptorHelper.class);

            HttpSession session = request.getSession(true);

            UserSummary user = (UserSummary) session.getAttribute(WebConstants.USER_DETAIL);

并且通过包含一个弹簧监听器,弹簧初始化首先发生。

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

这行得通。 但是我不是注入,而是显式加载依赖项。 有没有更好的方法来做到这一点?

【讨论】:

    猜你喜欢
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 2016-06-09
    • 2017-04-04
    相关资源
    最近更新 更多