Tag Archives: jee

CDI – DIY – Manual Injection

Enterprise development can be good and bad: It may support you with great managed environments, awesome conventions and configuration possibilities. But sometimes it also forces you into too tight railings, thinking it would be for your best, having you answering: “Wait… why… WTF?”

Unmanaged Dependency Injection

One trend especially jumps between brilliance and madness: Dependency Injection! To feature a common, broad context management supporting your needs with simple references, view and scope management is something very intriguing. But beware if you only peak out the window for once… it will immediately drop all its support for you and your code.

A managed environment can be supportive in many ways and eases our every day life but often misses the scope of Software Engineering and its possible uses. This leads to limitations or horrible inter-configuration-setup-libraries architecture that no one can manage but god himself.

Manual Dependency Injection

Therefore, it might happen that you have to jump between e.g. two components of managed and unmanaged source, in desperate need to access the managed environment. For that you can manually check the registered BeanManager and grab your managed resources yourself.

public BeanManager getBeanManager() {
	try {
		return (BeanManager) new InitialContext().lookup("java:comp/BeanManager");

	} catch (NamingException e) {
		return null;

By checking the local context and grabbing the BeanManager you have the foundation to fiddle around and grasp of the managed entities.

With the BeanManager you are now able to look up the managed beans by class or name and iterate over what you are looking for. Below you can find an example how to look for the first managed bean of a given class, if any.

public  T getBean(Class beanClass) {
	BeanManager beanManager = getBeanManager();
	if(beanManager != null) {
		Set> beans = beanManager.getBeans(beanClass);
		if(beans != null && !beans.isEmpty()) {
			Bean bean = (Bean) beanManager.getBeans(beanClass).iterator().next();
			CreationalContext ctx = beanManager.createCreationalContext(bean);
			return (T) beanManager.getReference(bean, beanClass, ctx);	
	return null;

Of course, I would always encourage to stay as managed as possible, if you develop in such an environment. But especially if you have to deal with legacy modules, or dedicate multi-purpose components (which I had to), this solution encapsulated in a utility helper can save you many brain cells and long evenings spending with real development ^^’.

Big thanks to Dominik Dorn for this life saving hint.