-
@description 测试@Import注解中使用ImportSelector
-
自定义逻辑,返回需要导入的组件
*/
public class MyImportSelector implements ImportSelector {
/**
-
返回值为需要导入到容器中的bean的全类名数组
-
AnnotationMetadata:当前标注@Import注解的类的所有注解信息
*/
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
return new String[0];
}
}
接下来,我们在PersonConfig2类的@Import注解中,导入MyImportSelector类,如下所示。
@Configuration
@Import({Department.class, Employee.class, MyImportSelector.class})
public class PersonConfig2 {
至于使用MyImportSelector导入哪些bean,就需要在MyImportSelector类的selectImports()方法中进行设置了,只要在MyImportSelector类的selectImports()方法中返回要导入的类的全类名(包名+类名)即可。
我们继承创建两个Java bean对象,分别为User和Role,如下所示。
- User类
package io.mykit.spring.plugins.register.bean;
/**
-
@author binghe
-
@version 1.0.0
-
@description 测试ImportSelector
*/
public class User {
}
- Role类
package io.mykit.spring.plugins.register.bean;
/**
-
@author binghe
-
@version 1.0.0
-
@description 测试ImportSelector
*/
public class Role {
}
接下来,我们将User类和Role类的全类名返回到MyImportSelector类的selectImports()方法中,此时,MyImportSelector类的selectImports()方法如下所示。
/**
-
返回值为需要导入到容器中的bean的全类名数组
-
AnnotationMetadata:当前标注@Import注解的类的所有注解信息
*/
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
return new String[]{
User.class.getName(),
Role.class.getName()
};
}
接下来,我们运行SpringBeanTest类的testAnnotationConfig7()方法,输出的结果信息如下所示。
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.anno 《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】 tation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
personConfig2
io.mykit.spring.plugins.register.bean.Department
io.mykit.spring.plugins.register.bean.Employee
io.mykit.spring.plugins.register.bean.User
io.mykit.spring.plugins.register.bean.Role
person
binghe001