首先@Import标签可以引入三种类,分别说明其作用
一.@Import(ImportSelector实现类.class)
实现接口ImportSelector,重写抽象方法selectImports,返回类全限定名字符串数组
下面针对返回类全限定名三种不同场景分析:
1.selectImports方法返回的类全限定名是普通类(即没有实现ImportSelector和ImportBeanDefinitionRegistrar接口)
①编写实现ImportSelector接口的子类MyImportSelector,重写抽象方法selectImports,返回普通类全限定名字符串
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
public class MyImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
//返回的User就是普通类
return new String[]{
"cn.zhutan.test.import_anno.User"};
}
}
②在测试类中,用@Import标签引入MyImportSelector
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Import;
@Import(value = {
MyImportSelector.class})
public class DemoTest {
@SuppressWarnings("resource")
public static void main(String[] args) {
ApplicationContext ac = new AnnotationConfigApplicationContext(DemoTest.class);
User user = ac.getBean(User.class);
System.out.println(user);
}
}
运行结果如下,表明可以从spring已经创建User对象,并且可以从容器中获取到User对象
结论:
当你返回的类是普通类时,spring后续就会根据你返回的类全限定名字符串解析和创建bean定义,创建bean对象等等一系列操作,然后放到spring容器中
2.返回的类是ImportSelector子类
①编写ImportSelector的子类OtherImportSelector,重写抽象方法selectImports,返回MyImportSelector全限定名字符串
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
public class OtherImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
//返回的MyImportSelector是实现了ImportSelector接口的类
//而MyImportSelector的selectImports方法又返回了User类
return new String[]{
"cn.zhutan.test.import_anno.MyImportSelector"};
}
}
②在测试类中,用@Import标签引入OtherImportSelector
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Import;
@Import(value = {
OtherImportSelector.class})
public class DemoTest {
@SuppressWarnings("resource")
public static void main(String[] args) {
ApplicationContext ac