Skip to content

Instantly share code, notes, and snippets.

@mariofts
Created August 12, 2014 21:10
Show Gist options
  • Save mariofts/d6d63871aacd65d9ebad to your computer and use it in GitHub Desktop.
Save mariofts/d6d63871aacd65d9ebad to your computer and use it in GitHub Desktop.
A CDI Service Locator to be used where injection is not available :(
package br.com.caelum.financas.util;
import java.util.Iterator;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class CDILocator {
private BeanManager getBeanManager(){
try {
return (BeanManager) InitialContext.doLookup("java:comp/BeanManager");
} catch (NamingException e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
public <T> T lookup(final Class<T> clazz) {
final BeanManager bm = getBeanManager();
final Iterator<Bean<?>> iter = bm.getBeans(clazz).iterator();
if (!iter.hasNext()) {
throw new IllegalStateException("CDI BeanManager cannot find an instance of requested type " + clazz.getName());
}
final Bean<T> bean = (Bean<T>) iter.next();
final CreationalContext<T> ctx = bm.createCreationalContext(bean);
return (T) bm.getReference(bean, clazz, ctx);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment