How to instantiate more CDI beans for one class?

后端 未结 1 904
庸人自扰
庸人自扰 2021-01-13 03:10

Note: The similar question has been already asked three years ago, in time of EE 6, see how to instantiate more then one CDI/Weld bean for one class? Has so

相关标签:
1条回答
  • 2021-01-13 03:23

    I would create qualifiers FooQualifier,HooQualifier and Producer for MyBean, something like this:

    @ApplicationScoped
    public class MyBeanProducer {
    
        @Produces
        @FooQualifier
        public MyBean fooProducer() {
            return new MyBean(42);
        }
    
        @Produces
        @HooQualifier
        public MyBean hooProducer() {
            return new MyBean(666);
        }
    }
    

    Then if you somewhere do:

        @Inject
        @FooQualifier
        private MyBean foo;
    

    You will have MyBean instance with foo.getSomeProperty() equal to 42 and if you do:

    @Inject
    @HooQualifier
    private MyBean hoo;
    

    you will have MyBean instance with foo.getSomeProperty() equal to 666.

    Another possibility is to have one configurable qualifier:

    @Target( { TYPE, METHOD, PARAMETER, FIELD })
    @Retention(RUNTIME)
    @Documented
    @Qualifier
    public @interface ConfigurableQualifier {
    
        @Nonbinding
        int value() default 0;
    }
    

    and then producer method:

    @Produces
    @ConfigurableQualifier
    public MyBean configurableProducer(InjectionPoint ip){
        int somePropertyValue = ip.getAnnotated().getAnnotation(ConfigurableQualifier.class).value();
        return new MyBean(somePropertyValue);
    }
    

    then simply calling:

    @Inject
    @ConfigurableQualifier(value = 11)
    private MyBean configurableBean;
    

    will result in MyBean instance with someProperty equal to 11.

    0 讨论(0)
提交回复
热议问题