How can I programmatically inject a Java CDI 1.1+ managed bean into a local variable in a static method?
A method annotated with @Inject that overrides another method annotated with @Inject will only be injected once per injection request per instance. A method with no @Inject annotation that overrides a method annotated with @Inject will not be injected. Injection of members annotated with @Inject is required.
As you may have noticed, the bean is nothing more than a plain old Java object, annotated with the @Dependent annotation. This annotation, called the dependent scope, declares that POJO is a CDI component. The dependent scope tells the CDI context to create a new instance whenever you request an injection to this bean.
A CDI bean is a POJO, plain old java object, that has been automatically instantiated by the CDI container, and is injected into all, and any qualifying injection points in the application. The CDI container initiates the bean discovery process during deployment.
To inject an instance of class C
:
javax.enterprise.inject.spi.CDI.current().select(C.class).get()
This is available in CDI 1.1+
Use for instance this utility class. You basically have to obtain instance of BeanManager
and than grab the bean you want from it (imagine something like JNDI lookup).
Update
You could also use CDI utility class offered in CDI 1.1
SomeBean bean = CDI.current().select(SomeBean.class).get();
Update 2
In CDI 2.0 you have to use BeanManager class for obtaining bean instances programatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With