Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually Register Class in CDI Container

Tags:

java

cdi

I have a group of classes which are instantiated by reflection, hence these are not managed by the CDI container, and no injections are made by the context. My question is, is there any way to register these classes in the CDI context, so the classes get managed by the context?

Bellow, is how I create the classes:

String clazz = "org.myorg.thisIsMyClass";
MyClass myClass = Class.forName(clazz).newInstance(); // myClass instance not managed by CDI

How do I make the instance of myClass managed by the CDI container?

like image 937
Joe Almore Avatar asked Apr 03 '14 20:04

Joe Almore


1 Answers

If your classes were registered as bean by the container you can use programmatic lookup to get them easily.

@Inject
@Any
Instance<Object> myBeans;

public Object getMyBeanFromClassName(String className) throws Exception{    
    Class clazz = Class.forName(className);
    return myBeans.select(clazz).get();  
}

Et voilà.

like image 87
Antoine Sabot-Durand Avatar answered Oct 15 '22 11:10

Antoine Sabot-Durand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!