依赖注入到ResourceFilter中不起作用? [英] Dependency injection into ResourceFilter not working?
问题描述
我有一堆JAX-RS资源,它们为新的WebService提供API.为了了解正在发生的事情,我想将有关每个请求的信息存储在数据仓库中.在我看来,这是跨领域关注的完美示例,可以通过ResourceFilter
来实现,对吧?
I have a bunch of JAX-RS resources that provide an API for a new WebService. In order to understand what's happening, I'd like to store information about each request in a data warehouse. In my mind, this is a perfect example for a cross-cutting concern, which could be implemented by a ResourceFilter
, right?
所以我建立了一个DataWarehouseService
,它应该将内容存储在数据库中:
So I built a DataWarehouseService
which is supposed to store stuff in the DB:
@Stateless
@LocalBean
public class DataWarehouseService {
public void logApiCall(ContainerRequest cr) {
// get interesting fields from request, store in DB
...
}
}
这是我的过滤器:
public class LoggingResourceFilter implements ResourceFilter {
Logger log = Logger.getLogger(this.getClass().getName());
@EJB
DataWarehouseService dwh;
@Override
public ContainerRequestFilter getRequestFilter() {
return new ContainerRequestFilter() {
@Override
public ContainerRequest filter(ContainerRequest cr) {
log.info("Incoming request: "+
cr.getHeaderValue("user-agent") +" "+
cr.getMethod() +" "+
cr.getPath()
);
dwh.logApiRequest(cr);
return cr;
}
};
}
@Override
public ContainerResponseFilter getResponseFilter() {
return null;
}
}
我通过类级别的注释@ResourceFilters(LoggingResourceFilter.class)
将过滤器注入到我的JAX-RS资源中.
I inject the filter into my JAX-RS resources via annotation @ResourceFilters(LoggingResourceFilter.class)
on class-level.
当我访问JAX-RS资源之一时,Filter-injection工作正常,日志语句("Incoming request:...")被执行.但是之后,立即使用Nullpointer调用注入的DataWarehouseService
的dwh.logApiRequest(cr)
失败-显然注入失败了!!
The Filter-injection works fine, when I access one of the JAX-RS resources, the log statement ("Incoming request: ...") gets executed. But immediately afterwards, the call to the injected DataWarehouseService
's dwh.logApiRequest(cr)
fails with a Nullpointer - obviously the injection failed?!
这是什么问题?我以为,ResourceFilters
是托管的,可以使用CDI.我错了吗?
What's the problem here? I thought, ResourceFilters
are managed and can use CDI. Am I wrong?
所有这些都在Glassfish 3.1.1上运行,Jersey 1.8是JAX-RS提供程序.如果我使用@Inject
会有所不同吗?
All of this runs on Glassfish 3.1.1, Jersey 1.8 is the JAX-RS provider. Would it make a difference if I used @Inject
?
推荐答案
好,我是个白痴.
在LoggingResourceFilter
上添加@Stateless
批注以对其进行修复.
Adding a @Stateless
annotation to the LoggingResourceFilter
fixed it.
这篇关于依赖注入到ResourceFilter中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!