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

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

问题描述

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

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

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

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

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

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

ADDED

让我举个例子。

<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:


  • 在没有进一步了解您的用例的情况下,我假设您要么为(模拟)测试或配置问题提供一些替代实现(比如说OrderService的另一个PaymentProvider)。这是由规范本身支持的,看看 @Alternative here (不要重复我最初的错误,忘记激活beans.xml中的替代品)

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

要获得Spring样式的XML配置,您可以使用 Seam 3配置,提供与配置一样的XML配置。顺便说一句,这是JSR 299的一部分,但无论出于何种原因已从规范中删除。

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天全站免登陆