• 10、组件注册-@Import-使用ImportBeanDefinitionRegistrar


    10、组件注册-@Import-使用ImportBeanDefinitionRegistrar

    public interface ImportBeanDefinitionRegistrar {
    
    	/**
    	 * Register bean definitions as necessary based on the given annotation metadata of
    	 * the importing {@code @Configuration} class.
    	 * <p>Note that {@link BeanDefinitionRegistryPostProcessor} types may <em>not</em> be
    	 * registered here, due to lifecycle constraints related to {@code @Configuration}
    	 * class processing.
    	 * @param importingClassMetadata annotation metadata of the importing class
    	 * @param registry current bean definition registry
    	 */
    	public void registerBeanDefinitions(
    			AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry);
    
    }
    

    10.1 实现ImportBeanDefinitionRegistrar 并重写 registerBeanDefinitionsfan方法

    package com.hw.springannotation.conditional;
    
    import com.hw.springannotation.beans.RainBow;
    import org.springframework.beans.factory.config.BeanDefinition;
    import org.springframework.beans.factory.support.BeanDefinitionRegistry;
    import org.springframework.beans.factory.support.RootBeanDefinition;
    import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
    import org.springframework.core.type.AnnotationMetadata;
    
    /**
     * @Description TODO
     * @Author hw
     * @Date 2018/11/28 16:16
     * @Version 1.0
     */
    public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
        /**
         * @param importingClassMetadata annotation metadata of the importing class 当前类的注解信息
         * @param registry               current bean definition registry   定义的注册类
         *                               所有需要添加到容器中的bean BeanDefinitionRegistry.registerBeanDefinition 手动注册进来
         */
        public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
            boolean red = registry.containsBeanDefinition("com.hw.springannotation.beans.Red");
            boolean blue = registry.containsBeanDefinition("com.hw.springannotation.beans.Blue");
    
            if (red && blue) {
                // 指定Bean的定义信息,Bean的类型,作用域等
                BeanDefinition beanDefinition = new RootBeanDefinition(RainBow.class);
                // 注册一个Bean,指定bean名
                registry.registerBeanDefinition("rainBow", beanDefinition);
            }
        }
    }
    
    

    10.2 使用

    新建RainBow类,并在MainConfig中导入MyImportBeanDefinitionRegistrar.class

    @Import({Color.class, Red.class, MyImportSelector.class, MyImportBeanDefinitionRegistrar.class})
    
    

    10.3 测试

  • 相关阅读:
    sass学习笔记1
    javascript 数组的深度复制
    div+css定位position详解
    滚动加载图片(懒加载)实现原理
    移动端布局经验
    js 扁平化输出数组
    axiso基本使用及python接收处理
    JSP内置对象
    JSP基本语法
    tomcat环境搭建
  • 原文地址:https://www.cnblogs.com/Grand-Jon/p/10025358.html
Copyright © 2020-2023  润新知