文章目录
最近在看springboot启动流程的时候,发现很多@EnableXX类型的注解,里面都有@Import注解;这里先简单总结下,import注解,其实就是导入配置类用的。
总结
value支持的三种类型:
1.带有@Congfiguration注解的类(spring4.2版本开始支持普通类);
比如EnableSwagger2的开启注解:
@Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(value = { java.lang.annotation.ElementType.TYPE })
@Documented
@Import({Swagger2DocumentationConfiguration.class})//看这里
public @interface EnableSwagger2 {
}
然后打开Swagger2DocumentationConfiguration这个类:
@Configuration
@Import({ SpringfoxWebMvcConfiguration.class, SwaggerCommonConfiguration.class })
@ComponentScan(basePackages = {
"springfox.documentation.swagger2.readers.parameter",
"springfox.documentation.swagger2.web",
"springfox.documentation.swagger2.mappers"
})
public class Swagger2DocumentationConfiguration {
就是带有@Configuration注解的类。
2.ImportSelector接口的实现;
比如springboot的@EnableAutoConfiguration注解:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)//看这里
public @interface EnableAutoConfiguration {
然后打开AutoConfigurationImportSelector这个类:
public class AutoConfigurationImportSelector
implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware,
BeanFactoryAware, EnvironmentAware, Ordered {
就是实现了DeferredImportSelector这个接口,然后DeferredImportSelector继承了ImportSelector接口。
public interface DeferredImportSelector extends ImportSelector {
3.ImportBeanDefinitionRegistrar接口的实现;
比如携程Apollo的@EnableApolloConfig注解:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({ApolloConfigRegistrar.class})//看这里
public @interface EnableApolloConfig {
String[] value() default {"application"};
然后打开ApolloConfigRegistrar这个类:
public class ApolloConfigRegistrar implements ImportBeanDefinitionRegistrar {
public ApolloConfigRegistrar() {
就是实现了ImportBeanDefinitionRegistrar。
至于@import的详细介绍,
见一篇写的非常好的帖子:https://blog.csdn.net/mamamalululu00000000/article/details/86711079