以编程方式将POJO转换为@Configuration Spring

时间:2017-06-23 14:51:17

标签: java spring spring-boot

给出一个课程:

class MyConfiguration {
    @Bean
    String bean() {
        return new String();
    }
}

您可能会注意到它没有@Configuration注释。

如何使其表现得像@Configuration注释,但添加?

@Bean注释应该 Lite Modehttps://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Bean.html

中工作

类似的东西:

@Configuration
class MainConfiguration {
    @Bean
    MyConfiguration myConfiguration() {
        MyConfiguration myConfiguration = do_some_spring_magic();
        // myConfiguration behaving like it's having @Configuration here
        return myConfiguration;
    }
}

1 个答案:

答案 0 :(得分:2)

我不明白你试图在这里实现的用例是什么..但是如果你正在寻找以编程方式将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;
    }
}

在您的情况下,类MyConfiguration中的bean定义可以按照下面的编程方式注册到spring上下文中。

http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/support/BeanDefinitionRegistryPostProcessor.html