Spring dynamic bean creation depending on other bean

拜拜、爱过 提交于 2020-02-02 11:13:08

问题


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.

来源:https://stackoverflow.com/questions/48537481/spring-dynamic-bean-creation-depending-on-other-bean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!