美文网首页Spring 学习
Spring 动态生成bean

Spring 动态生成bean

作者: 砺豪 | 来源:发表于2017-07-25 16:17 被阅读1214次
    @Configuration
    public class DanyConfig implements ApplicationContextAware {
    
        private static ApplicationContext applicationContext=null;
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            this.applicationContext=applicationContext;
        }
    
    
        public  static ApplicationContext getApplicationContext(){
            return applicationContext;
        }
    }
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class DanyTest {
    
    
    
        @Test
        public void test(){
            ConfigurableApplicationContext context = (ConfigurableApplicationContext)  DanyConfig.getApplicationContext();
            //Bean的实例工厂
            DefaultListableBeanFactory dbf = (DefaultListableBeanFactory) context.getBeanFactory();
            //Bean构建  BeanService.class 要创建的Bean的Class对象
            BeanDefinitionBuilder dataSourceBuider = BeanDefinitionBuilder. genericBeanDefinition(BeanService.class);
            //向里面的属性注入值,提供get set方法
            dataSourceBuider.addPropertyValue("msg", "hello ");
            //dataSourceBuider.setParentName("");  同配置 parent
            //dataSourceBuider.setScope("");   同配置 scope
            //将实例注册spring容器中   bs 等同于  id配置
            dbf.registerBeanDefinition("beanService", dataSourceBuider.getBeanDefinition());
    
            BeanService beanService=(BeanService) context.getBean("beanService");
            beanService.say();
            
        }
    
    
    }
    
    
    class BeanService  {
        private String msg;
        public String getMsg() {
            return msg;
        }
        public void setMsg(String msg) {
            this.msg = msg;
        }
        public void say(){
            System.out.println("====="+msg);
        }
    
    }
    

    相关文章

      网友评论

        本文标题:Spring 动态生成bean

        本文链接:https://www.haomeiwen.com/subject/nhzwkxtx.html