JAX-RS:自定义类对象没有注入ContainerRequestFilter [英] JAX-RS: Custom class object no injected into a ContainerRequestFilter

查看:591
本文介绍了JAX-RS:自定义类对象没有注入ContainerRequestFilter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个 ContainerRequestFilter 实现,如下所示:

I've created an ContainerRequestFilter implementation like this:

@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 字段。

As you can see I'm trying to inject a MemcachedApplicationResources object into memcachedResources field.

MemcachedApplicationResources 类似于:

@ApplicationScoped
public class MemcachedApplicationResources {}

为什么 null

编辑

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

I've just created a beans.xml file with this content:

<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

我还尝试创建过滤器而不是 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!
    }
}

为什么使用过滤器类是否注入了字段?

Why using a Filter class the field is injected?

推荐答案

如果符合以下情况,注入应该有效:

The injection should work if:


  • WEB-INF beans.xml 文件c>(对于CDI 1.2不是强制性的)。

  • 您的过滤器是由CDI管理的bean。

  • You have a beans.xml file under WEB-INF (not mandatory for CDI 1.2).
  • Your filter is a bean managed by CDI.

根据您的容器,您可能需要额外的依赖关系才能使CDI与RESTEasy一起使用,但它应该与WildFly一起开箱即用。请参阅文档更多细节。

Depending on your container, you may require an extra dependency to make CDI works with RESTEasy, but it should work out-of-the-box with WildFly. See the documentation for more details.

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

If it doesn't work, you still can try to get the instance programmaticaly using:

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

这篇关于JAX-RS:自定义类对象没有注入ContainerRequestFilter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆