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);
        }
    }

結果如圖:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM