@SpringBootApplication 包含的三个注解及其含义

一、@SpringBootApplication 注解源码
java 复制代码
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.boot.autoconfigure;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.TypeExcludeFilter;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.core.annotation.AliasFor;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
    // ... ...
}

从源码中可知,@SpringBootApplication 包含的三个注解是 @SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan。

二、@SpringBootApplication包含的三个注解及其含义
  1. @SpringBootConfiguration(该类的源码中又有一个 @Configuration 的注解)

@Configuration 这个注解的作用就是声明当前类是一个配置类,然后 Spring 会自动扫描到添加了 @Configuration 的类,读取其中的配置信息,而 @SpringBootConfiguration 是来声明当前类是 SpringBoot 应用的配置类,项目中只能有一个。所以一般我们无需自己添加。

  1. @EnableAutoConfiguration

开启自动配置,告诉 SpringBoot 基于所添加的依赖,去 "猜测" 你想要如何配置 Spring。比如我们引入了 spring-boot-starter-web,而这个启动器中帮我们添加了 tomcat、SpringMVC的依赖,此时自动配置就知道你是要开发一个 web 应用,所以就帮你完成了 web 及 SpringMVC 的默认配置了!我们使用 SpringBoot 构建一个项目,只需要引入所需框架的依赖,配置就可以交给 SpringBoot 处理了。

  1. @ComponentScan

配置组件扫描的指令。

提供了类似于 <context:component-scan> 标签的作用。

通过 basePackageClasses 或者 basePackages 属性来指定要扫描的包。

如果没有指定这些属性,那么将从声明这个注解的类所在的包开始,扫描包及子包。

而我们的 @SpringBootApplication 注解声明的类就是 main 函数所在的启动类,因此扫描的包是该类所在包及其子包。因此,一般启动类会放在一个比较靠前的包目录中。

相关推荐
你曾经是少年3 分钟前
Java 关键字
java
海南java第二人6 分钟前
SpringBoot启动流程深度解析:从入口到容器就绪的完整机制
java·开发语言
问今域中8 分钟前
Spring Boot 请求参数绑定注解
java·spring boot·后端
星火开发设计10 分钟前
C++ queue 全面解析与实战指南
java·开发语言·数据结构·c++·学习·知识·队列
rgeshfgreh12 分钟前
Java+GeoTools+PostGIS高效求解对跖点
java
鱼跃鹰飞13 分钟前
DDD中的防腐层
java·设计模式·架构
计算机程序设计小李同学15 分钟前
婚纱摄影集成管理系统小程序
java·vue.js·spring boot·后端·微信小程序·小程序
栈与堆1 小时前
LeetCode 19 - 删除链表的倒数第N个节点
java·开发语言·数据结构·python·算法·leetcode·链表
一路向北·重庆分伦1 小时前
03-01:MQ常见问题梳理
java·开发语言
一 乐1 小时前
绿色农产品销售|基于springboot + vue绿色农产品销售系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·后端·宠物