-2

I have a similiar problem cited in this post:

But, I need to use the producer method for create complex object (this object receive two params in constructor). Using the producer method to lose reference to the interceptor. I found nothing in the specification of the CDI who said that the interceptors are not performed on objects generated by the producer methods.

My question is: Its possible use producer method and keeping the reference with interceptors?

Community
  • 1
  • 1
Luciano
  • 3
  • 5
  • 1
    If you have the same problem, the answer to the other question should answer yours. If you have a different problem, please post code snippets, what you have tried and what kind of errors you get to help people answer your question. As it is your question is very hard to answer. See also http://stackoverflow.com/help/how-to-ask – Buurman Nov 05 '15 at 12:58
  • I edit a question to clear it. – Luciano Nov 05 '15 at 13:13

1 Answers1

0

CDI interceptors and decorators are only applied to beans that are instantiated by the CDI container.

However, there is an ugly workaround. It's a bit technical but bear with me. I'm writing this mostly without an IDE so I apologise for typos and such, it's just to give you an idea.

First you'll need to create a qualifier

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.PARAMETER})
public @interface InjectionParameter {
    int value();
}

Then you'll need to annotate your special constructor like this:

@Inject
public MyClass(@InjectionParameter(1) Object firstParam, @InjectionParameter(2) Object secondParameter)

Then for your producer you say

@Inject
private Instance<MyClass> myClassInstance;

@Produces
@InjectionParameter(1)
Object firstParam;

@Produces
@InjectionParameter(2)
Object secondParam;

@Produces MyClass producer() {
    firstParam = null; /* set your first param here */
    secondParam = null; /* set your second param here */
    return myClassInstance.get();
}

Note that my use of Object was just an example, please replace with your own actual types :)

The point is that the CDI container CAN instantiate beans that don't have a default constructor as long as the proper constructor is annotated with @Inject and each parameter is a valid injection target. What I did there was set up the parameters of your bean through producer fields.

Note that I didn't actually test this with a CDI container so you may have to fine tune the solution. You might end up with ambiguous bean resolution between the producer method and the bean itself, which you can resolve by putting another qualifier on the bean and in the producer class's instance field.

Hope this helps. -Juuso

jvalli
  • 721
  • 4
  • 7