Skip to content

Instantly share code, notes, and snippets.

@raphw
Created May 15, 2020 13:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raphw/eaf809da5d9287ccc855101d24d51480 to your computer and use it in GitHub Desktop.
Save raphw/eaf809da5d9287ccc855101d24d51480 to your computer and use it in GitHub Desktop.
Bean registration example
class MyAutoConfiguration {
@Bean
public static BeanFactoryPostProcessor behandleserviceRegistrationBeanFactory() {
return factory -> {
if (!(factory instanceof BeanDefinitionRegistry)) {
throw new IllegalStateException("Unsupported bean factory: " + factory.getClass().getTypeName());
}
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) factory;
String someBean = Arrays.stream(factory.getBeanNamesForType(SomeBeanType.class)).findFirst().orElseThrow();
Arrays.stream(factory.getBeanNamesForType(SomeLegacyThing.class)).forEach(name -> {
BeanDefinition definition = factory.getBeanDefinition(name);
String value;
if (definition instanceof AnnotatedBeanDefinition && definition.getSource() instanceof MethodMetadata) {
MethodMetadata beanMethod = (MethodMetadata) definition.getSource();
if (beanMethod.isAnnotated(SomeAdditionalData.class.getName())) {
Map<String, Object> attributes = beanMethod.getAnnotationAttributes(SomeAdditionalData.class.getName());
value = (IdentifikatorType) attributes.get("value");
} else {
throw new IllegalStateException("Bean " + name + " lacks " + SomeAdditionalData.class.getTypeName() + " annotation");
}
} else {
throw new IllegalStateException("Unsupported declaration of bean " + name);
}
registry.registerBeanDefinition(
name + "BeanFactory",
BeanDefinitionBuilder
.genericBeanDefinition(NewStuffBeanFactory.class)
.setScope(BeanDefinition.SCOPE_SINGLETON)
.addConstructorArgReference(someBean)
.addConstructorArgReference(name)
.addConstructorArgValue(value)
.getBeanDefinition()
);
});
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment