码迷,mamicode.com
首页 > 编程语言 > 详细

Spring基础-BeanDefinitionRegistryPostProcessor实现动态添加到spring容器

时间:2018-06-28 00:55:27      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:reg   i++   each   table   nbu   ide   values   cto   registry   

定义一个bean

public class Person {

    private  String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name=‘" + name + ‘\‘‘ +
                ‘}‘;
    }
}

然后实现BeanDefinitionRegistryPostProcessor 

@Component
public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        for (int i = 0; i < 10; i++) {
            BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(Person.class);
            builder.addPropertyValue("name", "sfz_" + i);
            registry.registerBeanDefinition("person" + i, builder.getBeanDefinition());
        }
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    }
}

这样就可以动态注入

public class App4 {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.fz.song.four");
        context.getBeansOfType(Person.class).values().forEach(System.out::println);

        context.close();
    }
}

第二种方式

public class App4 {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.fz.song.four");
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(Person.class);
        builder.addPropertyValue("name","songfazhun");
        context.registerBeanDefinition("Person_app",builder.getBeanDefinition());

        context.getBeansOfType(Person.class).values().forEach(System.out::println);


        context.close();
    }
}

 

 

顺便提一提BeanFactoryPostProcessor

@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        int beanDefinitionCount = beanFactory.getBeanDefinitionCount();
        System.out.println("beanDefinitionCount = " + beanDefinitionCount);
    }
}

这个是在spring容器初始化的时候调用的

Spring基础-BeanDefinitionRegistryPostProcessor实现动态添加到spring容器

标签:reg   i++   each   table   nbu   ide   values   cto   registry   

原文地址:https://www.cnblogs.com/songfahzun/p/9236656.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!