Contexts and Dependency Injection (CDI)

Optional Bean Reference Injection

Springs @Autowired annotation supports optional bean injection (required=false). If you want to simulate a similar behaviour with CDI you must inject an instance of the optional bean and check its availability.

public class OptionalBeanProducer {

    @Inject
    private Instance<OptionalBean> optionalBeanInstance;

    @Produces
    public OptionalBean produceOptionalBean() {
        return optionalBeanInstance.isUnsatisfied() ? null : optionalBeanInstance.get();
    }

}

Logger Injection

Most Java developers instantiate Loggers in a static way.

private static final Logger LOGGER = LoggerFactory.getLogger(MyClass.class);

Using CDI in this case is much more flexible. Furthermore, it is possible to replace the logger by mock objects during testing. That helps a lot when you have to verify the log output in your test.

public class LoggerProducer {

	@Produces
	Logger produceLogger(InjectionPoint injectionPoint) {
		return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
	}
}
@Named
public class MyService {

	@Inject
	private Logger logger;

	...
}

BeanManager Access

Not all implementations support injection via CDI. In those cases it can help to lookup required resources via BeanManager. There are different ways to get access to the BeanManager.

return InitialContext.doLookup("java:comp/BeanManager");
return CDI.current().getBeanManager();