如何为一个类实例化一个以上的CDI/Weld bean? [英] how to instantiate more than one CDI/Weld bean for one class?

查看:85
本文介绍了如何为一个类实例化一个以上的CDI/Weld bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Spring中,可以通过在xml conf中定义相应的bean来实例化任何类.对于具有不同参数的同一类,还可以实例化多个bean.

CDI中是否也具有这样的功能,即是否可以使用不同的初始化参数创建同一类的不同实例?

是否可以在不更改类的情况下创建一个bean....我的意思是不添加注释?

添加

让我举一个例子.

<bean id="someBean1" class="org.mm.MyBean">
    <property name="x" value="xx"/>
    <property name="y" value="yy"/>
    <property name="z" value="zz"/>       
</bean>
<bean id="someBean2" class="org.mm.MyBean">
    <property name="x" value="other value"/>
    <property name="y" value="yy2"/>
    <property name="z" value="zz2"/>       
</bean>

如何实例化同一类的两个实例并用不同的字段值初始化它们?

解决方案

据我所知,有两个选择:

  • 在不进一步了解用例的情况下,我假设您想为(模拟)测试或配置问题提供某种替代实现(例如,针对OrderService的另一个PaymentProvider).规范本身对此提供支持,请查看@Alternative 此处(不要重复我最初的错误,而忘记在beans.xml中激活替代方案)

  • 要获取Spring样式的XML配置,您可以使用 Seam 3 Config ,就像描述的那样提供XML配置.顺便说一句,这已成为JSR 299的一部分,但由于任何原因已从规范中删除.

In Spring it was possible to instantiate any class by defining the corresponding bean in xml conf. It was also possible to instantiate more then one bean for the same class with different parameters.....

Are the such features in CDI as well, namely is it possible to create different instances of the same class with different initialization parameters?

Is it also possible to create a bean without changing the class....I mean without adding annotation?

ADDED

Let me make an example.

<bean id="someBean1" class="org.mm.MyBean">
    <property name="x" value="xx"/>
    <property name="y" value="yy"/>
    <property name="z" value="zz"/>       
</bean>
<bean id="someBean2" class="org.mm.MyBean">
    <property name="x" value="other value"/>
    <property name="y" value="yy2"/>
    <property name="z" value="zz2"/>       
</bean>

How can instantiate two instances of the same class and initialize them with different field values?

解决方案

Two options as far as I can see:

  • Without further knowledge of your usecase, I assume that you either want to provide some alternative implementation for (mock-) testing or configuration issues (say another PaymentProvider for a OrderService). This is supported by the spec itself, have a look at @Alternative here (and don't repeat my initial mistake and forget to activate alternatives in beans.xml)

  • To get a Spring-style XML-configuration, you can use Seam 3 Config, which provides XML-configuration just as described. BTW, this has been a part of JSR 299, but has been removed from the spec for whatever reason.

这篇关于如何为一个类实例化一个以上的CDI/Weld bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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