美文网首页
Spring 的动态注册方式

Spring 的动态注册方式

作者: 幽澜先生 | 来源:发表于2019-07-18 11:05 被阅读0次

    方法一 :
    定义一个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.youlanai.com.du");
            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();
        }
    }
    
    

    相关文章

      网友评论

          本文标题:Spring 的动态注册方式

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