我创建了一个 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
对象注入(inject)到 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
类来注入(inject)字段?
最佳答案
如果出现以下情况,注入(inject)应该有效:
- 您在
WEB-INF
下有一个beans.xml
文件(对于 CDI 1.2 不是必需的)。 - 您的过滤器是由 CDI 管理的 bean。
根据您的容器,您可能需要额外的依赖项才能使 CDI 与 RESTEasy 一起工作,但它应该与 WildFly 一起开箱即用。查看documentation了解更多详情。
如果它不起作用,您仍然可以尝试使用以下方法以编程方式获取实例:
MemcachedApplicationResources bean =
CDI.current().select(MemcachedApplicationResources.class).get();
关于jakarta-ee - JAX-RS:自定义类对象未注入(inject) ContainerRequestFilter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45755377/