@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 函数所在的启动类,因此扫描的包是该类所在包及其子包。因此,一般启动类会放在一个比较靠前的包目录中。

相关推荐
AI人工智能+电脑小能手1 分钟前
大白话说Java设计模式-08-建造者模式(业务实战篇)
java·设计模式·建造者模式·架构设计·对象构建
xbgRS11 分钟前
java中的线程
java
今天的砖头有点烫手啊26 分钟前
接口太慢?Spring Boot 缓存体系 @Cacheable 全链路拆解
spring boot·后端·缓存
ChaHae-In1 小时前
MyBatis入门操作
java·mybatis
xcLeigh1 小时前
Go入门:短变量声明的陷阱与最佳实践
java·redis·golang·教程·变量
青山木1 小时前
Hot 100 --- 最小栈
java·数据结构·算法·leetcode
疯狂打码的少年1 小时前
【数据结构】栈的应用:表达式求值(后缀表达式)
java·数据结构·笔记·算法
szephyr1 小时前
腾讯云 ADP 智能体的 Skills 版本回滚总是回到旧配置,是缓存没清还是版本管理没开?
java·缓存·腾讯云
云烟成雨TD1 小时前
Micrometer 系列【39】链路追踪:入门案例 | 环境准备
java·云原生·链路追踪
chuan.bai1 小时前
Java RAG 实战(第 3 篇):从交互式聊天到多轮上下文
java·人工智能·macos·ai