【Spring注解驱动开发】在

  • @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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值