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

相关推荐
灿飞屋22 分钟前
Kotlin与Java虚拟机三:控制流
android·java·开发语言·后端·python·kotlin·安卓
NE_STOP1 小时前
Spring AI Alibaba - MCP入门
java
nice_lcj5201 小时前
【从零理解 Spring AI · 07】对话记忆:让模型记住上一句说了什么
java·spring ai·ai应用开发·chatmemory·对话记忆
SL_staff2 小时前
制造业交付崩盘?用跨部门节点协同计划打通销售、生产与质量链路
java·开源·产品
文丑颜不良啊3 小时前
LeetCode2261~2280题目解析
java·leetcode
SL_staff3 小时前
告别规则黑盒:JVS-Rules 在金融风控中的可视化决策编排实践
java·产品·全栈
逆回3 小时前
升级 Boot 4 后,我的 mock 全红了
spring boot
逃逸线LOF4 小时前
服务网关Gateway
java·运维·gateway
灿飞屋4 小时前
Kotlin与Java虚拟机四:函数
java·python·kotlin·安卓·android jetpack
阡陌数智5 小时前
Claude API新版本重大变更与安全升级指南
java·linux·安全