简体   繁体   中英

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.

How can I make it behave like it has @Configuration annotation, but not adding it?

@Bean annotation should not work in 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.

@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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM