@Import注解

1.代码

1. Type级别注解,可以作用于类 接口(包括注解类型) 枚举 上声明

2.注解保留策略:编译后存在于class文件中,且能在运行时被虚拟机保留,所以可以反射读取

3.value属性 Class数组 :@Configuration, ImportSelector, ImportBeanDefinitionRegistrar,或者要导入的常规组件类。可以导入@Configuration注解修饰的配置类,ImportSelector接口实现类,以及ImportBeanDefinitionRegistrar接口实现类,或者是常规的组件类

 

 2.注释解析

 Indicates one or more component classes to import — typically @Configuration classes.

表示一个或者多个组件类去导入一个类,而这个类通常是@Configuration修饰的类

Provides functionality equivalent to the <import/> element in Spring XML. Allows for importing @Configuration classes, ImportSelector and ImportBeanDefinitionRegistrar implementations, as well as regular component classes (as of 4.2; analogous to AnnotationConfigApplicationContext.register).

提供相当于Spring XML中的<import/>元素的功能。允许导入@Configuration类,ImportSelector和ImportBeanDefinitionRegistrar实现类,以及常规组件类(截至4.2;类似于AnnotationConfigApplicationContext.register)。

@Bean definitions declared in imported @Configuration classes should be accessed by using @Autowired injection.

Either the bean itself can be autowired, or the configuration class instance declaring the bean can be autowired.

The latter approach allows for explicit, IDE-friendly navigation between @Configuration class methods.

在导入的@Configuration类中声明的@Bean定义应该通过使用@Autowired注入来访问。

bean自己可以被注入,或者配置类实例声明的bean可以被注入

后一种方法允许在@Configuration类方法之间进行显式的、ide友好的导航。

May be declared at the class level or as a meta-annotation.

可以被声明在类级别或者元注解级别

If XML or other non-@Configuration bean definition resources need to be imported, use the @ImportResource annotation instead.

如果需要导入XML或其他非@Configuration bean定义资源,请使用@ImportResource注释。

3.代码实例(SpringBoot中使用)

1.在@Configuration注解声明的配置类中导入常规类,常规类会被注入到容器中

 2.在@Configuration注解声明的配置类中导入实现ImportBeanDefinitionRegistra接口registerBeanDefinitions方法的类,在此方法中将ClassCC注册到容器中,ClassCC会被注入到容器中

  3.在@Configuration注解声明的配置类中导入实现ImportSelector接口selectImports方法的类,在此方法中将ClassBB返回,ClassBB会被注入到容器中

 最后项目启动输出所有容器中的类

 

 

posted @ 2023-08-02 21:05  1024荀  阅读(188)  评论(0)    收藏  举报