CDI - Producers and Qualifiers not on the produced object

675 views Asked by At

imagine having a producer for a SessionFactory (as example):

@Produces public SessionFactory produceSessionFactory(){}

No I have a second producer that produces some other object, lets say a DatabaseObject, and needs a reference to a SessionFactory:

@Produces
public DatabaseObject produceDatabaseObject(SessionFactory factory){}

No I can use my database object like that:

@Inject
DatabaseObject object;

So far, so good. So lets assume this stuff is implemented in a framework and is going to be used by several applications.

Now one application decides it wants to use another SessionFactory, so it implements its own producer and a qualifier:

@Produces 
@CustomQualifier
public SessionFactory produceSessionFactory(){}

But now, as far as I know, I could not use a DatabaseObject with the qualifier, because - of course - the qualifier is just used at a producer for the SessionFactory. So this wont work:

@Inject
@CustomQualifier
DatabaseObject object;

By consequence the application would have to reimplement the DatabaseObject producer, having the absolutely same code, or extending the base producer and just adding the qualifier:

@Produces
@CustomQualifier
public DatabaseObject produceDatabaseObject(@CustomQualifier SessionFactory factory){
    return super.produceDatabaseObject(factory);
}

This somehow produces boilerplate code from my point of view and gets hilarious if you have a lot of producers.

Is there a way to achieve this without the need to reimplement the producer? So that basically the producer method gets injected the SessionFactory regarding the qualifier on the object it produces?

Thank you!

1

There are 1 answers

1
mp911de On

You can use InjectionPoint in your producers to retrieve qualifiers and create appropriate instances (see https://docs.jboss.org/weld/reference/latest/en-US/html/injection.html#_the_literal_injectionpoint_literal_object for example).

Alternatively, create a portable extension. By doing so, you can register/create own beans. Creating extensions for just a couple of beans might be too costly for too less benefit, but look yourself here: https://docs.jboss.org/weld/reference/latest/en-US/html/extend.html#_registering_a_literal_bean_literal