CDI - Producers and Qualifiers not on the produced object

你离开我真会死。 提交于 2019-12-12 01:24:22

问题


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:


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



来源:https://stackoverflow.com/questions/31007892/cdi-producers-and-qualifiers-not-on-the-produced-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!