Spring的@Import注解四种使用方式
来介绍@Import
注解的使用之前,我们先看源码:
从注释中,我们可以看到@Import
注解可以将@Configuration
、ImportSelector、ImportBeanDefinitionRegistrar和普通的component类导入。
准备Spring环境
Spring依赖
导入@Configuration类
需要导入的bean:Hello
配置类:HelloConfiguration
启动类:SpringTestApplication
启动之后,控制台输出如下:
说明Hello对象确实通过@Import
注解注入到了容器中。
导入ImportSelector
ImportSelector实现类:HelloImportSelector
ImportSelector
是一个接口,实现这个接口需要重写selectImports
方法。
selectImports
方法会返回一个String数组。
下面我们实现ImportSelector
接口并重写selectImports
方法,将Hello
类的全限定名返回。
启动类:SpringTestApplication
启动之后,控制台输出如下:
导入ImportBeanDefinitionRegistrar
ImportBeanDefinitionRegistrar实现类:HelloImportDefinitionRegistrar
启动类:SpringTestApplication
启动之后,控制台输出如下:
直接导入Bean
启动类:SpringTestApplication
启动之后,控制台输出如下:
hello word
Process finished with exit code 0