Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAX-RS: Custom class object no injected into a 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.
    }
}

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

MemcachedApplicationResources is like:

@ApplicationScoped
public class MemcachedApplicationResources {}

Why is it null?

EDIT

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>

However, it's still null.

enter image description here

EDIT 2

I've also tried to create an Filter instead of a 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?

like image 503
Jordi Avatar asked Nov 22 '25 15:11

Jordi


1 Answers

The injection should work if:

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

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();
like image 82
cassiomolin Avatar answered Nov 25 '25 09:11

cassiomolin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!