zoukankan      html  css  js  c++  java
  • 9、组件注册-@Import-使用ImportSelector

    9、组件注册-@Import-使用ImportSelector

    9.1 @Import 源码:

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface Import {
    
    	/**
    	 * {@link Configuration}, {@link ImportSelector}, {@link ImportBeanDefinitionRegistrar}
    	 * or regular component classes to import.
    	 */
    	Class<?>[] value();
    
    }
    

    可以使用ImportSelector来注册组建

    public interface ImportSelector {
    
    	/**
    	 * Select and return the names of which class(es) should be imported based on
    	 * the {@link AnnotationMetadata} of the importing @{@link Configuration} class.
    	 */
    	String[] selectImports(AnnotationMetadata importingClassMetadata);
    
    }
    

    9.2 自定义逻辑返回需要注入的组建

    新建 MyImportSelector implements ImportSelector 重写selectImports 方法。

    package com.hw.springannotation.conditional;
    
    import org.springframework.context.annotation.ImportSelector;
    import org.springframework.core.type.AnnotationMetadata;
    
    /**
     * @Description 自定义逻辑返回需要注入的组建
     * @Author hw
     * @Date 2018/11/28 15:52
     * @Version 1.0
     */
    public class MyImportSelector implements ImportSelector {
        /**
         * 返回值就是需要导入的组建 全类名
         *
         * @param importingClassMetadata 当前标注@Import注解类的所有注解信息
         */
        public String[] selectImports(AnnotationMetadata importingClassMetadata) {
            // 不能返回null
            return new String[]{"com.hw.springannotation.beans.Blue"};
        }
    }
    

    9.3 引入@Import

    @Import({Color.class, Red.class, MyImportSelector.class})    // 快速导入组建,ID 默认是全路径包名
    
    

    9.4 运行测试类

        /**
         * @Import注解
         */
        @Test
        public void testImport() {
            printBeans();
    //        System.exit(0);
        }
    
        private void printBeans(){
            String[] names = applicationContext.getBeanDefinitionNames();
            for (String name : names) {
                System.out.println(name);
            }
        }
    

    结果如图:

  • 相关阅读:
    sprintboot 发布
    springmvc 常用注解
    react-navigation使用技巧
    Windows 10提示你不能访问此共享文件夹,因为你组织的安全策略阻止未经身份验证的来宾访问
    Python 精选文章
    自动化办公:python操作Excel
    VSCode 插件
    使用 Visual Studio Code(VSCode)搭建简单的Python+Django开发环境的方法步骤
    纯洁的微笑
    初进python世界之数据类型
  • 原文地址:https://www.cnblogs.com/Grand-Jon/p/10025349.html
Copyright © 2011-2022 走看看