JAX-RS:自定义类对象没有注入ContainerRequestFilter

时间:2017-08-18 11:18:22

标签: java-ee jax-rs cdi

我已经创建了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

enter image description here

编辑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类注入字段?

1 个答案:

答案 0 :(得分:0)

注射应该起作用:

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

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

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

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