I want do create a CDI factory using @Produces annotation on a method in order to look up a named something in an external service and return (produce) a proxy to this something in the external service to be injected into other beans. From a use case point of view, usually all these dependencies are required; however it happens sometimes that the requested something does not exist in the remote service and the application can react to this fact.
Basically the structure is like this:
@Singleton public class SomeBean {
@Inject @MyName("required") private Something requiredSomething;
@Inject @MyName("optional") private Instance<Something> optionalSomething;
@PostConstruct void init() {
if (optionalSomething.isUnSatisfied()) {
// act without optional Something in external service
} else {
optionalSomething.get().doWhatIWant(NOW);
}
}
}
@ApplicationScoped
public class SomethingFactory {
@Inject private RemoteSomethingService remoteService;
@Produces
@MyName(value = "")
public Something createRemoteSomething(InjectionPoint injectionPoint) {
MyName name = injectionPoint.getAnnotated().getAnnotation(MyName.class);
Something some = remoteService.lookup(name.value()); // throws an exception if lookup fails
return some;
}
}
This works in cases the injection on the side that uses somethings is required: successfull lookups inject the looked up Something instance, while unsuccessful lookups break the bean bootstrapping. However, in cases of an optional injection with a non-existent something, it either breaks because Instance.isUnSatisfied() returns false. If I leave createRemoteSomething() throwing the exception, this exception is raised during the call to optionalSomething.get(); if I return null instead, the same call leads to a NPE.
How to achieve this using CDI primitives? Thanks.