Skip to content

Instantly share code, notes, and snippets.

@canwe
Forked from mojavelinux/StartupBean.java
Created April 5, 2018 10:16
Show Gist options
  • Save canwe/8aa1ba1e4e04bc097a605225b39f183e to your computer and use it in GitHub Desktop.
Save canwe/8aa1ba1e4e04bc097a605225b39f183e to your computer and use it in GitHub Desktop.
A sample CDI extension for eagerly instantiating @ApplicationScoped beans annotated @startup
@ApplicationScoped
@Startup
public class StartupBean
{
@PostConstruct
public void onStartup()
{
System.out.println("Application starting up.");
}
}
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