Skip to content

Instantly share code, notes, and snippets.

@ljnelson
Last active February 11, 2017 20:17
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/6ab593ede76f6ad34c48a67c1202011c to your computer and use it in GitHub Desktop.
Save ljnelson/6ab593ede76f6ad34c48a67c1202011c to your computer and use it in GitHub Desktop.
private final void installConfigurationValueProducerMethods(@Observes final AfterBeanDiscovery event, final BeanManager beanManager) {
if (event != null && beanManager != null) {
// Get a Configurations object.
final Instance<Object> i = beanManager.createInstance();
assert i != null;
final Instance<Configurations> configurationsInstance = i.select(Configurations.class);
assert configurationsInstance != null;
if (configurationsInstance.isResolvable()) {
final Configurations configurations = configurationsInstance.get();
assert configurations != null;
// Find out its set of Types.
final Set<Type> types = configurations.getConversionTypes();
if (types != null && !types.isEmpty()) {
// Create a BeanAttributes representing our almost-producer method.
final AnnotatedType<ConfigurationsExtension> thisType = beanManager.createAnnotatedType(ConfigurationsExtension.class);
final AnnotatedMethod<? super ConfigurationsExtension> producerMethod = thisType.getMethods().stream()
.filter(m -> m.getJavaMember().getName().equals("produceConfigurationValue"))
.findFirst()
.get();
final BeanAttributes<?> producerAttributes = beanManager.createBeanAttributes(producerMethod);
for (final Type type : types) {
assert type != null;
// For each type, create a Bean representing it.
// The bean will be logically comprised of the BeanAttributes we made above, but
// with its type set appropriately, and a ProducerFactory representing our
// almost-producer method. The combination will make this a "real" Bean
// thus turning our almost-producer method into a "real" producer method.
final Bean<?> bean =
beanManager.createBean(new DelegatingBeanAttributes<Object>(producerAttributes) {
@Override
public final Set<Type> getTypes() {
final Set<Type> types = new HashSet<>();
types.add(Object.class);
types.add(type);
return types;
}
},
ConfigurationsExtension.class,
beanManager.getProducerFactory(producerMethod, null /* null OK; producer method is static */));
// Add the Bean representing the almost-producer method to the container;
// the almost-producer method will now handle injection points of the
// current type!
event.addBean(bean);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment