Last active
April 14, 2021 15:44
-
-
Save joelbinn/5023363 to your computer and use it in GitHub Desktop.
Get CDI bean from bean manager.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
How to get a CDI bean instance via the bean manager.