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

结果如图:

1221855-20181128160603971-129202139.png

转载于:https://www.cnblogs.com/Grand-Jon/p/10025349.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值