CDI-生产者和合格者不在生产对象上 [英] CDI - Producers and Qualifiers not on the produced object

查看:139
本文介绍了CDI-生产者和合格者不在生产对象上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象有一个SessionFactory的生产者(例如):

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

@Produces public SessionFactory produceSessionFactory(){}

不,我还有第二个生成器,它可以生成其他对象,可以说是DatabaseObject,并且需要对SessionFactory的引用:

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.

现在,一个应用程序决定要使用另一个SessionFactory,因此它实现了自己的生产者和限定符:

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

@Produces 
@CustomQualifier
public SessionFactory produceSessionFactory(){}

但是,据我所知,我现在不能将DatabaseObject与限定符一起使用,因为-当然-限定符仅在SessionFactory的生产者处使用.所以这行不通:

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;

结果是,应用程序必须重新实现DatabaseObject生产者,使用完全相同的代码,或者扩展基本生产者并仅添加限定符:

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.

是否有一种方法可以实现这一目标而无需重新实现生产者?这样,基本上,生产者方法就可以在其产生的对象上注入有关限定符的SessionFactory?

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?

谢谢!

推荐答案

您可以使用

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).

或者,创建一个可移植扩展.这样,您可以注册/创建自己的bean.仅为几个bean创建扩展可能太昂贵而带来的好处却太少,但请在此处查看:

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

这篇关于CDI-生产者和合格者不在生产对象上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆