精通 Spring 源码 | ImportSelector

本文介绍了 Spring 中的 ImportSelector 扩展点,它用于实现类似 @EnableXXX 功能。通过分析 ImportSelector 接口及其 selectImports 方法,展示了如何自定义 ImportSelector 并创建示例,解释了如何利用该机制动态控制类的注入。通过 @Import 注解结合自定义注解 @EnableHly,控制 IndexDao 类是否被注入到 Spring 容器。测试结果显示,开启 @EnableHly 时正常工作,否则报错。
摘要由CSDN通过智能技术生成
一、简介

ImportSelector 是Spring的扩展点之一,这个扩展点有什么用呢,如果说在 SpringBoot 中,我们熟悉的 @EnableXXX 就是通过这个扩展点来实现的,下面我们来进行分析和实现。

下面是他的源码,在 Spring 中是一个接口,具体有什么用呢

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

}

她提供了一个方法 selectImports 可以返回一个字符串数组,Spring 会把这个数组里面的对象注入到 Spring 容器中去,所以,我们可以灵活的实现 @EnableXXX 的功能。下面我们来实现一个例子。

二、示例

定义需要注入的类,我们定义了两个类 UserDao 和 IndexDao,UserDao 注入容器,IndexDao 不注入容器

@Component
public class UserDao {

}
public class IndexDao {
}

我们再定义一个 MyImportSelector 实现 ImportSelector ,这里动态返回了 IndexDao ,说明会把这个类注入到 Spring 容器中去。

public class MyImportSelector implements ImportSelector {
	@Override
	public String[] selectImports(AnnotationMetadata importingClassMetadata) {

		return new String[]{IndexDao.class.getName()};
	}
}

我们再来自定义一个注解,@Import 表明会把 MyImportSelector.class 注入到容器中去,所以这里我们定义的 @EnableHly 就一个开关,是否把 IndexDao 注入到容器中。

@Import(MyImportSelector.class)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface EnableHly {
}

最后再定义我们的配置类 ,@EnableHly 打开开关,才会注入 IndexDao 。

@Configuration
@ComponentScan("com.javahly.spring26")
@EnableHly
public class AppConfig {
}

测试

public class Test {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
		System.out.println(applicationContext.getBean(UserDao.class));
		System.out.println(applicationContext.getBean(IndexDao.class));

	}
}

如果使用 @EnableHly 打开开关,则正常输出

com.javahly.spring26.dao.UserDao@1888ff2c
com.javahly.spring26.dao.IndexDao@35851384

否则,报错

com.javahly.spring26.dao.UserDao@6ea6d14e
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.javahly.spring26.dao.IndexDao' available

演示完毕

—— 完

ABOUT

公众号:【星尘Pro】
github:https://github.com/huangliangyun

推荐阅读
史上最全,最完美的 JAVA 技术体系思维导图总结,没有之一!
全站导航 | 文章汇总!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

星尘Pro

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值