问题
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