Skip to content

Instantly share code, notes, and snippets.

@ljnelson
Last active January 16, 2019 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ljnelson/8f7007417c3916e36ba70ea2f363cae3 to your computer and use it in GitHub Desktop.
Save ljnelson/8f7007417c3916e36ba70ea2f363cae3 to your computer and use it in GitHub Desktop.
// Here's a neat way to ask an Application for its classes and singletons
// before the CDI container is up. That should let you register only those
// beans that should be registered.
private static final <T extends Application> void registerClassesAndSingletons(final AfterBeanDiscovery event,
final Bean<T> bean,
final BeanManager beanManager)
{
Objects.requireNonNull(event);
Objects.requireNonNull(bean);
Objects.requireNonNull(beanManager);
// The contexts aren't active yet, so we can't use Context's get()
// methods. Instead, we're going to ask the Bean to create an
// instance of the Application (this also handles injection
// partially; i.e. non-synthetic beans are available to be
// injected but synthetic beans are not). We'll ask the new
// Application instance, which is effectively unmanaged, for its
// classes and singletons. We'll register all those under the
// same qualifiers that they might have already plus the ones
// present on their governing Application. Then we destroy this
// unmanaged Application instance.
final CreationalContext<T> cc = beanManager.createCreationalContext(bean);
final T application = bean.create(cc);
if (application != null) {
final Set<Class<?>> classes = application.getClasses();
if (classes != null && !classes.isEmpty()) {
for (final Class<?> cls : classes) {
if (cls != null) {
event.addBean()
.scope(Dependent.class)
.read(beanManager.createAnnotatedType(cls))
.addQualifiers(bean.getQualifiers());
}
}
}
final Set<?> singletons = application.getSingletons();
if (singletons != null && !singletons.isEmpty()) {
for (final Object singleton : singletons) {
if (singleton != null) {
event.addBean()
.scope(Singleton.class)
.read(beanManager.createBeanAttributes(beanManager.createAnnotatedType(singleton.getClass())))
.qualifiers(bean.getQualifiers())
.createWith(ignored -> singleton);
}
}
}
}
bean.destroy(application, cc);
cc.release();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment