直接上代码:
//1.获取context:ConfigurableApplicationContext.其中applicationContext 可以是注入的
ApplicationContext applicationContext = getApplicationContext();
ConfigurableApplicationContext configFcaotry = applicationContext instanceof
ConfigurableApplicationContext ? ((ConfigurableApplicationContext) applicationContext) : null;
//2.获取factory:DefaultListableBeanFactory
ConfigurableListableBeanFactory beanFactory =configFcaotry.getBeanFactory();
DefaultListableBeanFactory listFacotry = beanFactory instanceof
DefaultListableBeanFactory ? ((DefaultListableBeanFactory) beanFactory) : null;
//3.动态构建bean:BeanDefinitionBuilder
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(DataSource.class)
.addPropertyValue("password", oriPwd + "@123");
AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
defaultListableBeanFactory.registerBeanDefinition("datasource",beanDefinition);