专业的编程技术博客社区

网站首页 > 博客文章 正文

认识 SpringBootApplication 注解

baijin 2025-03-25 10:49:13 博客文章 10 ℃ 0 评论

@SpringBootApplication

标识被注解的类是一个 @Configuration 类,在类中可以声明一个或多个 @bean 方法,并且它会触发 @EnableAutoConfiguration 和 @ComponenetScan 注解的相应功能。@SpringBootApplication 注解是一个综合性注解,等同于同时声明 @Configuration、@EnableAutoConfiguration 和 @ComponentScan 这三个注解。

@SpringBootApplication

在 @SpringBootApplication 的类声明中没有看到 @Configuration 注解,那是因为 @SpringBootConfiguration 注解本身其实就是一个 @Configuration 注解。至于 @EnableAutoConfiguration 注解的魔法功能将在在下面会说到。

这篇文章不谈论具体背后的工作原理,只是先认识根 @SpringBootApplication 注解相关的其他几个注解,以及带来的作用。先把地基打好,才能建高楼大厦。

@Import

@Import 注解表示可以导入一个或多个 @Configuration 类。它提供的功能等同于以前的 Spring xml 配置中的 <import /> 标签,可以导入 @Configuration 类、ImportSelector 和
ImportBeanDefinitionRegistrar 的实现类
,以及普通的组件类。如果 XML 或其他非 @Configuration 注解定义的 bean 资源需要被导入,可以使用 @ImportResource 注解。

ImportSelector

ImportSelector

  1. org.springframework.context.EnvironmentAware
  2. org.springframework.beans.factory.BeanFactoryAware
  3. org.springframework.beans.factory.BeanClassLoaderAware
  4. org.springframework.context.ResourceLoaderAware

ImportBeanDefinitionRegistrar

ImportBeanDefinitionRegistrar

它的作用是在处理 @Configuration 时,注册额外的 bean definition。

@EnableAutoConfiguration

EnableAutoConfiguration

开启 Spring 应用上下文的自动配置功能,它试图猜测你可能需要配置的 bean 信息。

@AutoConfigurationPackage

AutoConfigurationPackage

表示包含该注解的类所在的包应该在 AutoConfigurationPackages 中注册。所以这个注解就能够解释为什么 spring boot 的启动类要放在 package 的最外层,以保证 spring 能够自动扫描到它们。

它的实现原理是在注解上标注了 @Import,导入了一个
AutoConfigurationPackages.Registrar 类。

AutoConfigurationPackages.Registrar

用于保存导入的配置类所在的包及子包。它实现了
ImportBeanDefinitionRegistrar 接口。注意下,Registrar 类是 AutoConfigurationPackages 类的内部类,同上面的注解 @AutoConfigurationPackage 名字就差了一个字母,千万别搞混了。

AutoConfigurationPackages.Registrar

AutoConfigurationImportSelector

AutoConfigurationImportSelector

DeferredImportSelector 类用于处理自动配置。如果需要自定义扩展 @EnableAutoConfiguration,那么也可以扩展此类。

DeferredImportSelector

DeferredImportSelector

DeferredImportSelector 接口是 ImportSelector 接口的一种扩展,它是在处理完所有 @Configuration 类型的 bean 之后才会被执行,因此,它的执行时机是在 @Configuration 注解中的其他逻辑被处理完毕之后(包括对 @ImportResource、@Bean 这些注解的处理)再执行,也就是说,DeferredImportSelector 的执行时机比 ImportSelector 更晚。

DeferredImportSelector 接口在处理有条件的选择导入时非常有用。

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表