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

相关推荐
xyy20252 分钟前
Spring事务的传播方式
java·数据库·spring
@Kerry~9 分钟前
phpstudy .htaccess 文件内容
java·开发语言·前端
roshy10 分钟前
x86、arm、rsc-v指令集架构,指令集、OS、应用3者的关系
java·arm开发·架构
CRMEB系统商城10 分钟前
CRMEB多商户系统(PHP)v3.3正式发布,同城配送上线[特殊字符]
java·开发语言·小程序·php
iナナ20 分钟前
Java优选算法——位运算
java·数据结构·算法·leetcode
毕设源码-钟学长27 分钟前
【开题答辩全过程】以 濒危动物保护管理系统为例,包含答辩的问题和答案
java·eclipse
Han.miracle1 小时前
数据结构二叉树——层序遍历&& 扩展二叉树的左视图
java·数据结构·算法·leetcode
Orange_sparkle1 小时前
若依使用基本步骤
java·vue
kevinfkq2 小时前
Java-idea编辑器中Jar方式打包启动
java·intellij-idea·jar
深色風信子2 小时前
SpringBoot 集成 LangChain4j RAG Redis 搜索
spring boot·langchain4j rag·rag redis 搜索·rag redis·springboot rag·rag 搜索