2

Is there a way to dynamically create a bean which is dependent on another one? I have a Spring Boot app which loads a configuration.xml file into a configuration bean. I want to have the configuration loaded once I try to create new dynamic beans dependent on that configuration bean.

What I have tried so far is to implement BeanDefinitionRegistryPostProcessor, but in the moment when I try to create a new GenericBeanDefinition, the configuration is not loaded yet. Here is my code:

@Component
public class MyPostProcessor implements BeanDefinitionRegistryPostProcessor {


    @Autowired
    private Configuration configuration;


     @Override
     public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            List<Cars> cars= configuration.getCars();
            for (Car car: cars) {
                  Motor motor = car.getMotor();
                  GenericBeanDefinition genericBeanDefinition = new GenericBeanDefinition();
                  genericBeanDefinition.setBeanClass(DynamicBean.class);
                  genericBeanDefinition.getConstructorArgumentValues().addGenericArgumentValue(motor);
                  ((BeanDefinitionRegistry) beanFactory).registerBeanDefinition(car.getId(), genericBeanDefinition);
                    }
     }

I get a NullPointerException here: List<Cars> cars= configuration.getCars();

Thanks.

VPK
  • 3,010
  • 1
  • 28
  • 35
Christina
  • 361
  • 1
  • 5
  • 17
  • have you tried [this method](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/support/AbstractBeanDefinition.html#setDependsOn-java.lang.String...-)? I mean using it like this: `genericBeanDefinition.setDependsOn` and so on – Dmitry Senkovich Jan 31 '18 at 08:21
  • You can use @Order annotation on your configuration classes to define load ordering. – Sahil Chhabra Jan 31 '18 at 08:44

0 Answers0