Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically inject a Java CDI managed bean into a local variable in a (static) method

How can I programmatically inject a Java CDI 1.1+ managed bean into a local variable in a static method?

like image 307
XDR Avatar asked Jul 17 '14 08:07

XDR


People also ask

How does @inject annotation work?

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.

Which annotation is used to instantiate CDI beans?

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.

What is CDI bean in Java?

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.


2 Answers

To inject an instance of class C:

javax.enterprise.inject.spi.CDI.current().select(C.class).get() 

This is available in CDI 1.1+

like image 82
XDR Avatar answered Sep 20 '22 18:09

XDR


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.

like image 20
Petr Mensik Avatar answered Sep 22 '22 18:09

Petr Mensik