目录
ImportBeanDefinitioRegistrar接口
value为ImportBeanDefinitionRegistrar接口类型
value为DeferredImportSelector接口类型
目前为止,注解的方式批量注册bean,我们介绍了2种方式:
- @Configuration结合@Bean注解的方式
- @CompontentScan扫描包的方式
但是也存在一定的局限性,我们来看看下面两种情况:
情况一:
如果需要注册的类是在第三方的jar中,那么我们如果想注册这些bean有2种方式:
- 通过@Bean的方式一个一个注册
- 通过@ComponentScan的方式。默认的@ComponentScan是无能为力的,他只能注册@Component,@Service等那四个注解标记的类,所以我们需要用自定义过滤器的方式
情况二:
通常我们的项目中有很多子模块,可能每个模块都是独立开发的,最后通过jar的方式引进来,每个模块中都有各自的@Configuration或者使用@CompontentScan标注的类,此时如果我们只想使用其中几个模块的配置类,怎么办?
@Import的使用
对于@Import,我们可以先来看看其源码:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Import {
/**
* {@link Configuration @Configuration}, {@link ImportSelector},
* {@link ImportBeanDefinitionRegistrar}, or regular component classes to
import.
*/
Class<?>[] value();
}
spring中对它的解释是:和xml配置的标签作用一样,允许通过它引入@Configuration标注的类 , 引入ImportSelector接口和ImportBeanDefinitionRegistrar接口的实现, 4.2版本以后也可以引入普通组件类
使用步骤:
- 将@Import标注在类上,设置value参数
- 将@Import标注的类作为AnnotationConfigApplicationContext构造参数创建 AnnotationConfigApplicationContext对象
- 使用AnnotationConfigApplicationContext对象
@import的value参数常见的六种用法
- value为普通的类
- value为@Configuration标注的类
- value为@CompontentScan标注的类
- value为ImportBeanDefinitionRegistrar接口类型
- value为ImportSelector接口类型
- value为DeferredImportSelector接口类型
value为普通类
public class Service1 {
}
public class Service2 {
}
@Import({Service1.class, Service2.class})
public class MainConfig1 {
}
class ImportTestApplicationTests {
@Test
void test1() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig1.class);
for (String beanName:context.getBeanDefinitionNames()){
System.out.println(beanName+"--->"+context.getBean(beanName));
}
}
}
运行后输出:
mainConfig1--->com.example.config.MainConfig1@76ed1b7c
com.example.service.Service1--->com.example.service.Service1@11fc564b
com.example.service.Service2--->com.example.service.Service2@394a2528
由输出结果可以看出:
- 我们使用@Import注解成功将普通类对象注册到容器了,但是这些bean的名称是全类名,如果我们想指定名称的话,在对应的类上加上@Component注解指定名称即可。
- 使用@Import的时候,也会连@Import标记的类一起注册到容器中。
value为@Configuration标注的类
@Configuration
public class ConfigModule1 {
@Bean
public String module1(){
return "我是模块一配置类";
}
}
@Configuration
public class ConfigModule2 {
@Bean
public String module2(){
return "我是模块二配置类";
}
}
@Import({ConfigModule1.class, ConfigModule2.class})
public class MainConfig2 {
}
class ImportTestApplicationTests {
@Test
void test1() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig2.class);
for (String beanName:context.getBeanDefinitionNames()){
System.out.println(beanNam