Created
October 20, 2010 03:41
-
-
Save mojavelinux/635719 to your computer and use it in GitHub Desktop.
A sample CDI extension for eagerly instantiating @ApplicationScoped beans annotated @startup
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
@ApplicationScoped | |
@Startup | |
public class StartupBean | |
{ | |
@PostConstruct | |
public void onStartup() | |
{ | |
System.out.println("Application starting up."); | |
} | |
} |
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
public class StartupBeanExtension implements Extension | |
{ | |
private final Set<Bean<?>> startupBeans = new LinkedHashSet<Bean<?>>(); | |
<X> void processBean(@Observes ProcessBean<X> event) | |
{ | |
if (event.getAnnotated().isAnnotationPresent(Startup.class) && | |
event.getAnnotated().isAnnotationPresent(ApplicationScoped.class)) | |
{ | |
startupBeans.add(event.getBean()); | |
} | |
} | |
void afterDeploymentValidation(@Observes AfterDeploymentValidation event, BeanManager manager) | |
{ | |
for (Bean<?> bean : startupBeans) | |
{ | |
// the call to toString() is a cheat to force the bean to be initialized | |
manager.getReference(bean, bean.getBeanClass(), manager.createCreationalContext(bean)).toString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can consider using the @initialized qualifier introduced in CDI 1.1 spec, and provided by the Weld implementation.
Here is a demo code: https://gist.github.com/sermojohn/c1044df560dbd86e4b9fae0283c64265