Reputation: 23247
I've created a ContainerRequestFilter
implementation. I'm facing up with some misunderstanding I don't quite solve.
This is my implementation:
@Provider
@PreMatching
@Secured
public class BearerFilter implements ContainerRequestFilter
{
@Context private HttpServletRequest request;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException
{
//this.request is null here
}
}
In order to register it on my jaxrs application:
@ApplicationPath(value = "cmng")
public class RestApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new HashSet<Class<?>>();
resources.add(AccountEndpoint.class);
//...
return resources;
}
@Override
public Set<Object> getSingletons() {
Set<Object> singletons = new HashSet<Object>();
singletons.add(new BearerFilter()); <<<<< manually created object.
return singletons;
}
}
So, BearerFilter
object is created manually, by code. The problem appears here since dependency injection only works on instances created and managed by the container itself.
So I'm not able to inject objects inside a ContainerRequestFilter
since it's not a created or managed object by container itself.
How could I solve that?
I'm using jaxrs.
Upvotes: 1
Views: 798
Reputation: 130927
The @Context
annotation is from JAX-RS and it's not related to CDI in any way. The available types that can be injected with @Context
can be seen in this answer.
According to the getSingletons()
method documentation, the injection should work:
Get a set of root resource, provider and feature instances. Fields and properties of returned instances are injected with their declared dependencies (see
Context
) by the runtime prior to use.
But you always can use the getClasses()
method to register your filter:
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<Class<?>>();
classes.add(AccountEndpoint.class);
classes.add(BearerFilter.class)
return classes;
}
From the documentation:
Get a set of root resource, provider and feature classes. The default life-cycle for resource class instances is per-request. The default life-cycle for providers (registered directly or via a feature) is singleton.
Upvotes: 1