users@jersey.java.net

[Jersey] Re: CDI in filters and exception mappers

From: Jakub Podlesak <jakub.podlesak_at_oracle.com>
Date: Mon, 6 Jan 2014 16:39:21 +0100

Hi Pedro,

Your understanding is correct. You should be able to inject using @Inject
into filters/exception mappers without any issues. Otherwise it is a bug.
I suspect something could be wrong with your producer, but i might be mistaken.
In that case i would need some more information, ideally a reproducible test case.

The HK2 exception that you see suggests that CDI does not know about your CDI producer.
Have you tried to just inject e.g. a raw CDI singleton bean (no CDI producer involved)?
Did it work?

In any way, could you please provide some more details on your injection point
and the producer that you believe should satisfy the injection point?

How do you register the producer? One way to do so, is to
1) implement you own CDI Extension
2) make the extension implement a “before bean discovery hook” like so:
    @SuppressWarnings("unused")
    private void beforeBeanDiscovery(@Observes BeforeBeanDiscovery beforeBeanDiscovery, BeanManager beanManager) {
        beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(YourLoggerProducer.class));
    }

Does the above fix your problem?

~Jakub

On 20 Dec 2013, at 11:55, Pedro Nuno Santos <pedro-n-santos_at_ptinovacao.pt> wrote:

> Hi,
>
> I’m not an expert on CDI (just learning the ropes) and I could be doing something wrong but shouldn’t I be able to use @Inject inside filters and/or exception mappers?
>
> I’ve tried both with glassfish 4.0 and 4.0.1 (using jersey 2.4.1) but injection only works inside resources. In both filters and exception mappers I get the following exception on deployment:
>
> org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee (…)
>
> The only solution I found was to use AbstractBinder to register the classes to be injected, however that doesn’t work if the object creation is being done using the @Produces annotation (I’m trying to inject a Logger instance and I need access to the class name where it’s injected, from what I can gather the hk2 Factories don’t allow me to access that information).
>
> I remember once reading in the documentation that any class annotated with “@Provider” supported CDI but I can’t seem to find the phrase anymore…
>
>
> Cheers,
> Pedro