Created
May 15, 2020 13:44
-
-
Save raphw/eaf809da5d9287ccc855101d24d51480 to your computer and use it in GitHub Desktop.
Bean registration example
This file contains 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
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