驽马十驾 驽马十驾

驽马十驾,功在不舍

目录
代码片段:Spring动态注入Bean
/  

代码片段:Spring动态注入Bean

直接上代码:

//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);
不积跬步,无以至千里。不积小流,无以成江海。