[英]Turn POJO to @Configuration programmatically Spring
Given a class: 给定一个班级:
class MyConfiguration {
@Bean
String bean() {
return new String();
}
}
as you may notice it does not have @Configuration
annotation. 您可能会注意到它没有@Configuration
批注。
How can I make it behave like it has @Configuration
annotation, but not adding it? 如何使其具有@Configuration
注解的行为,但不添加它?
@Bean
annotation should not work in Lite Mode
, https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Bean.html @Bean
注释不应该在工作的Lite Mode
, https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Bean.html
Something like: 就像是:
@Configuration
class MainConfiguration {
@Bean
MyConfiguration myConfiguration() {
MyConfiguration myConfiguration = do_some_spring_magic();
// myConfiguration behaving like it's having @Configuration here
return myConfiguration;
}
}
I dont understand what is the use case you are trying to achieve here.. But if you are looking for programatically registering beans into the Spring Context then you can do it as below. 我不明白您要在此处实现的用例是什么。.但是,如果您正在寻找以编程方式将bean注册到Spring Context中的方法,则可以按照以下步骤进行操作。
@Configuration
public class MyBeanRegisterFactory implements BeanDefinitionRegistryPostProcessor, PriorityOrdered {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanRegistry) throws BeansException {
//depending on some condition you can do the below line
beanRegistry.registerBeanDefinition("myBeanClass", new RootBeanDefinition("com.mybean.MyBeanClass"));
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
}
In Your case, the bean definitions inside the class MyConfiguration can be programatically registered as below into to the spring context. 在您的情况下,类MyConfiguration内的Bean定义可以如下编程地注册到spring上下文中。
http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/support/BeanDefinitionRegistryPostProcessor.html http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/support/BeanDefinitionRegistryPostProcessor.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.