ImportSelector接口是spring boot提供的接口,包含一个用于代码方式注册多个bean的方法,spring boot内部的DeferredImportSelector就是该接口的变种
用法:
1、定义MyImportSelector,并重写其 selectImports方法,这个方法就可以用于注册 bean :
将需要注册的bean的路径加类名放入selectImports方法返回的字符串数组即可。
public class MyImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
return new String[]{"com.example.demo.beans.User", User.class.getName()};
}
}
2、将这个类注册到容器中
随便找一个自己的自定义配置类,然后用@Import注解导入
@Import({MyImportSelector.class})
@Configuration
public class MyConfiguration {
}
注意:不能单纯的在我们写的ImportSelector类上用@Component注解来注册
原因:虽然@Import和@Component作用都是将类的实例注册进容器,但只用@Component注解注册时不会调用里面的selectImports方法,这样数组里的字符串就不会被注册成bean。
@Import是种更灵敏的方式,比如想把源码中的某个类注册为bean时,由于无法修改源码的缘故就无法在类名上加@Component注解,我们就可以用@Import(类名.class)来导入