【问题标题】:JAX-RS: Custom class object no injected into a ContainerRequestFilterJAX-RS:自定义类对象没有注入到 ContainerRequestFilter
【发布时间】:2018-01-27 01:33:51
【问题描述】:

我创建了一个像这样的ContainerRequestFilter 实现:

@Provider
@PreMatching
@Secured
@Dependent
public class BearerFilter implements ContainerRequestFilter
{

    @Inject protected MemcachedApplicationResources memcachedResources;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException
    {
        //this.memcachedResources is null here.
    }
}

如您所见,我正在尝试将MemcachedApplicationResources 对象注入memcachedResources 字段。

MemcachedApplicationResources 就像:

@ApplicationScoped
public class MemcachedApplicationResources {}

为什么是null?

编辑

我刚刚创建了一个包含以下内容的beans.xml 文件:

<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">

</beans>

不过,还是null。

编辑 2

我也尝试过创建Filter 而不是ContainerRequestFilter:

@WebFilter(
    dispatcherTypes = {DispatcherType.REQUEST },
    urlPatterns = { "/cmng/*" },
    initParams = { @WebInitParam(name = "excludedPaths", value = "log") }
    )
public class BearerWebFilter implements Filter
{

    @Inject protected MemcachedResources memcachedResources;

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
    {
        //here, this.memcachedResources is a injected proxy!
    }
}

为什么使用Filter 类来注入字段?

【问题讨论】:

  • 你的beans.xml喜欢什么?
  • 我没有任何beans.xml 文件。
  • 如果您不使用 CDI 1.2,beans.xml 是强制性的。否则注入将不起作用。
  • 我正在使用与 JAX-RS 无关的实现。目前,我在 Wildfly 10.1.0.Final 上部署我的 Web 应用程序,该版本具有最新的 RestEasy 实现。
  • 对于您的 Web 应用程序,在 WEB-INF 文件夹下创建一个空的 beans.xml 文件。

标签: jakarta-ee jax-rs cdi


【解决方案1】:

如果满足以下条件,注入应该可以工作:

  • WEB-INF 下有一个 beans.xml 文件(CDI 1.2 不是强制性的)。
  • 您的过滤器是由 CDI 管理的 bean。

根据您的容器,您可能需要额外的依赖项才能使 CDI 与 RESTEasy 一起使用,但它应该与 WildFly 一起开箱即用。有关详细信息,请参阅documentation。


如果它不起作用,您仍然可以尝试使用以下方式以编程方式获取实例:

MemcachedApplicationResources bean = 
    CDI.current().select(MemcachedApplicationResources.class).ge‌​t();

【讨论】:

  • 我再次编辑了帖子。基本上,我创建了一个Filter 类而不是ContainerRequestFilter。现在它起作用了。有什么想法吗?
  • @Jordi 现在可以了。有什么想法吗? CDI 注入在 servlet(和 servlet 过滤器)中开箱即用。
  • 但是,为什么它不能使用 JAXRS ContainerRequestFilter 工作?项目是一样的……
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-28
  • 2011-07-23
  • 1970-01-01
  • 1970-01-01
  • 2019-08-10
相关资源
最近更新 更多