how to instantiate more then one CDI/Weld bean for one class?

柔情痞子 提交于 2019-12-01 05:19:54

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.

there are a few ways to do that.

E.g. use @New

private @Inject @New YourBean yb; private @Inject @New YourBean yb2;

This forces the container to create a new instance, regardless what Scope the bean originally had.

Another way would be to simply define YourBean as being @Dependent scoped (which is btw (currently) the default if a class is not annotated at all).

You can easily use producer methods and if you have multiple instances that should be produced by a method use CDI qualifiers to distinguish different types of instances.

Also you can use Seam Config to do it Spring way but i think producer methods are more elegant way of doing this. depending on your use case there is another option which is @Alternative .

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