I have a class that is instantiated by 3rd party code (it uses reflection to create the object.) I provide the implementation of their interface and they create the object. In my implementation I want to use CDI to inject a service that performs logic. What is the correct way to do this?
public interface ThirdPartyInterface {
public void DoSomething();
}
public class InjectedService {
public void DoSomeLogic() { ... }
}
public class MyImplementation implements ThirdPartyInterface {
@Inject InjectedService service;
@Override
public void DoSomething() {
service.DoSomeLogic();
}
}
I originally thought this would work through the magic of CDI, but found my service object to be null.
The only thing I've come up with so far is to inject the service manually in the constructor
public MyImplementation() {
CDI<Object> cdi = CDI.current();
service = cdi.select(InjectedService.class).get();
}
Is this the correct/only/best way of obtaining the instance? I am using Weld for my CDI implementation.
I have also found this to work in the constructor:
public MyImplementation() {
CDI<Object> cdi = CDI.current();
BeanManager bm = cdi.getBeanManager();
AnnotatedType<MyImplementation> myType = bm.createAnnotatedType(MyImplementation.class);
Set<Bean<?>> beans = bm.getBeans(MyImplementation.class);
Bean<?> bean = bm.resolve(beans);
@SuppressWarnings("unchecked")
CreationalContext<MyImplementation> cc = (CreationalContext<MyImplementation>)bm.createCreationalContext(bean);
bm.createInjectionTarget(myType).inject(this, cc);
}