Skip to content

Instantly share code, notes, and snippets.

@canwe
Forked from joelbinn/ManagerUI.java
Created May 28, 2019 13:07
Show Gist options
  • Save canwe/873e73f19326c8327906037ad6dc3d5d to your computer and use it in GitHub Desktop.
Save canwe/873e73f19326c8327906037ad6dc3d5d to your computer and use it in GitHub Desktop.
Get CDI bean from bean manager.
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;
:
private static BeanManager getBeanManager() {
try {
InitialContext initialContext = new InitialContext();
return (BeanManager) initialContext.lookup("java:comp/BeanManager");
} catch (NamingException e) {
throw new RuntimeException(e);
}
}
public static <T> T getFacade(Class<T> clazz) {
BeanManager bm = getBeanManager();
Bean<T> bean = (Bean<T>) bm.getBeans(clazz).iterator().next();
CreationalContext<T> ctx = bm.createCreationalContext(bean);
T object = (T) bm.getReference(bean, clazz, ctx);
return object;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment