当前位置: 代码网 > it编程>编程语言>Java > Spring Boot场景启动器(Starters)从入门到精通

Spring Boot场景启动器(Starters)从入门到精通

2025年10月31日 Java 我要评论
什么是场景启动器?定义:场景启动器(starters) 是 spring boot 的核心特性之一,是一组预定义的依赖描述符(maven工程),可以简化maven配置。它们通常提供了一种“

什么是场景启动器?

定义:
场景启动器(starters)spring boot 的核心特性之一,是一组预定义的依赖描述符(maven工程),可以简化maven配置。它们通常提供了一种“一站式”服务,预先添加所有必要的依赖来使用某个特定的功能,可以轻松地将相关技术栈集成到项目中。

  • 例如,如果你想要使用springjpa进行数据库访问,你只需要添加spring-boot-starter-data-jpa依赖即可,它会自动引入所有相关的依赖。

核心理念:

  • 开箱即用:添加一个 starter 即可获得完整的技术栈支持
  • 依赖管理:自动解决版本兼容性问题
  • 自动配置:基于 classpath 自动配置相关组件

优势: 简化整合、简化开发、简化配置

简化整合(项目依赖):

  • springboot提供了一种场景启动器机制。
  • 场景启动器就是人为创建的maven整合工程。
  • 场景启动器中包含某个场景(方向)所有的依赖和配置类。
  • 场景启动器可以在普通maven工程使用,也可以在springboot工程使用
  • springboot工程才能发挥最大的功能:批量依赖导入、配置类自动加载
  • 官方场景启动器命名:spring-boot-starter-xxx
  • 非官方场景启动器命名:xxx-spring-boot-starter

简化开发(核心组件):

  • 无需我们写任何的配置类和配置文件(ioc)
  • springboot在场景启动器中已经提供所有的配置类
  • springboot框架自动配置功能(原理)
  • springboot自动配置原理会按需加载配置类,按需将组件加入到核心容器
  • 我们只需要专注业务逻辑编写即可。

简化配置(配置文件):

  • 固定配置文件的名称和格式。application.properties.yaml
  • 固定了部分功能的key(直接设置即可)
  • 固定的key大部分都有默认值(约定大于配置)
  • 不仅可以使用@value注解单个读取,还可以使用@configurationproperties注解批量读取

下面列出一些常见的spring boot场景启动器:

  • spring-boot-starter: 核心启动器,包括自动配置支持、日志和yaml。
  • spring-boot-starter-web: 用于构建web应用程序,包括restful应用程序,使用spring mvc。默认使用tomcat作为内嵌容器。
  • spring-boot-starter-data-redis: 使用redis和spring data redis。
  • spring-boot-starter-security: 使用spring security进行身份验证和授权。
  • spring-boot-starter-thymeleaf: 使用thymeleaf视图构建web应用程序。
  • spring-boot-starter-test: 用于测试spring boot应用程序,包括junit、hamcrest和mockito。
  • spring-boot-starter-actuator: 添加生产就绪功能,如监控和管理应用程序。
  • spring-boot-starter-undertow: 使用undertow作为内嵌容器(替代tomcat和jetty)。
  • spring-boot-starter-log4j2: 使用log4j2进行日志记录。

除了官方提供的启动器,还有很多第三方启动器,例如:

  • mybatis-spring-boot-starter: 用于集成mybatis。
  • druid-spring-boot-starter: 用于集成阿里巴巴的druid数据源。

官方和第三方的场景启动器区别?

  • 官方启动器的前缀为:spring-boot-starter,后跟项目名称
  • 第三方启动器的前缀为:项目名称-spring-boot-starter
  • mybatis是第三方场景启动器,它与web格式的区别在于它的名称在前面。
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-web</artifactid>
        </dependency>
        <dependency>
            <groupid>org.mybatis.spring.boot</groupid>
            <artifactid>mybatis-spring-boot-starter</artifactid>
            <version>3.0.5</version>
        </dependency>

springboot父项目spring-boot-starter-parent主要作用?

我们创建springboot项目时,通常会导入spring-boot-starter-parent场景启动器作为父项目,帮助我们管理并简化依赖的版本号。我们在确定要导入的spring-boot-starter-parent版本后,后续的导入的依赖就不需要写入版本信息了,spring-boot-starter-parent启动器会帮我们选择合适的场景启动器的版本好信息。

spring-boot-starter-parent底层是如何帮助我们实现的场景启动器版本管理呢?

  • 首先spring-boot-starter-parent场景启动器继承自spring-boot-dependencies,而spring-boot-dependencies的内部通过使用dependencymanagement来管理这些依赖的版本号。
  • 也就是说实际完成版本号管理的是spring-boot-dependencies工程。
  • spring-boot-starter-parent的管理版本号的功能继承自spring-boot-dependencies
  • spring-boot-starter-parent主要功能在于管理一些通用的构建配置,比如默认的编译器版本、资源过滤、插件配置等。

这样的设计是为了将依赖管理(dependency management)和插件配置等分开,使得项目结构更清晰。

在 spring boot 的源码中,spring-boot-starter-parent 的 pom.xml 中确实指定了其父项目为 spring-boot-dependencies

这样的层次结构有以下好处:

  1. spring-boot-dependencies 主要定义了依赖管理(dependencymanagement)和插件管理(pluginmanagement),即所有 依赖的版本号插件的版本号
  2. spring-boot-starter-parent 则继承自 spring-boot-dependencies,并添加了一些通用的构建配置,比如默认的编译器版本、资源过滤、插件配置等。
  3. 当用户项目继承 spring-boot-starter-parent 时,不仅获得了依赖版本管理,还获得了一些构建相关的默认配置。

所以,我们可以这样理解:

  • spring-boot-dependencies:定义了所有依赖的版本,即一个大的依赖管理矩阵。
  • spring-boot-starter-parent:在依赖管理的基础上,增加了默认的构建配置(如 maven 插件配置、资源过滤等)。

如果你查看 spring-boot-starter-parent 的 pom.xml,你会看到它并没有重复定义依赖版本,而是通过继承 spring-boot-dependencies 来获得所有版本管理。同时,它定义了一些其他元素,比如:

  • 默认的 java 版本
  • 资源过滤(包括占位符解析)
  • 插件配置(如 spring-boot-maven-plugin 的默认配置)

因此,当我们在项目中继承 spring-boot-starter-parent 时,我们实际上同时获得了依赖管理和构建配置两方面的便利。

如果你不能继承 spring-boot-starter-parent(比如已经有一个父项目),那么你可以通过引入 spring-boot-dependencies 的依赖管理来获得版本管理,但是构建配置就需要自己处理了。

总结:spring-boot-starter-parent 的父工程是 spring-boot-dependencies,前者继承了后者的依赖管理,并补充了构建配置。

这也就是为什么在springboot工程中,很多依赖不需要写版本号信息的原因。

maven从0开始搭建springboot项目

1. pom文件导入springboot父依赖

  • 导入父依赖。
    <parent>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-parent</artifactid>
        <version>3.5.7</version>
        <relativepath/> <!-- lookup parent from repository -->
    </parent>

spring-boot-starter-parent专业特性

  • 依赖管理(dependency management):统一管理所有spring boot相关依赖的版本
  • 插件配置(plugin configuration):预配置maven插件,如spring-boot-maven-plugin
  • 资源过滤(resource filtering):自动处理配置文件中的占位符替换
  • 属性配置(property configuration):预定义java版本、编码等构建属性

spring-boot-starter-parent优势:

  • 开箱即用:不用操心版本兼容
  • 配置齐全:插件、编码、java版本都配好了
  • 社区标准:遵循spring boot官方最佳实践
  • 减少错误:避免手动配置出错

导入场景启动器

    <dependencies>
    		<!--spring mvc场景启动器-->
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-web</artifactid>
        </dependency>
    </dependencies>

2. 编写springbootapplication启动类

我们通常将带有@springbootapplication注解的类称为启动类(或主类),它是spring boot应用的入口点。

启动器类是一个配置类(configuration class),通过组合注解自动配置机制,引导 spring 容器的启动过程,实现零配置或最小配置的应用启动

  • 使用springboot注解@springbootapplication修饰类文件。
  • 在入口函数main()方法处,它会创建一个ioc容器
@springbootapplication
public class mainapplication {
    public static void main(string[] args) {
    	// 启动tomcat和ioc容器
        springapplication.run(mainapplication.class, args);
    }
}

3. 创建控制器,测试springboot项目能否正常启动

  • 访问链接:localhost:8080/user/info,测试项目是否启动成功。
@restcontroller
@requestmapping("user")
public class usercontroller {
    @requestmapping("info")
    public string info(){
        return "hello";
    }
}

springboot整合spring mvc

spring boot 整合 spring mvc 非常简便,因为 spring boot 已经为 spring mvc 提供了自动配置。

  • 我们只需要导入spring-boot-starter-web场景启动器即可。
  1. 创建springboot项目,导入web场景启动器。
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-web</artifactid>
        </dependency>
  1. 编写控制器controller
@restcontroller
@requestmapping("user")
public class usercontroller {
    @getmapping("info")
    public string info(){
        return "user";
    }
    @getmapping("login")
    public string login(){
        return "login";
    }
}
  1. 访问控制器地址
  • http://localhost:8080/user/info

什么是 webmvcconfigurer?

webmvcconfigurer 是 spring mvc 框架中的一个核心接口,它提供了回调方法,允许开发者在 spring mvc 自动配置的基础上进行定制化扩展

  • webmvcconfigurerspring mvc 中用于自定义配置的核心接口,它提供了一种方式来自定义 spring mvc 的行为,而无需完全重写自动配置。
  • spring boot 中,自动配置已经为我们配置好了 spring mvc 的大部分默认行为,但如果你需要添加拦截器、格式化器、视图控制器等,就可以通过实现 webmvcconfigurer 接口来定制
  • 我们通常使用webmvcconfigurer来配置spring mvc,它替代了传统的xml配置方式。在spring boot中,我们通过实现webmvcconfigurer接口并重写所需的方法来定制mvc配置,比如拦截器、资源处理、跨域配置等。

主要意义:

  1. 提供集中化的配置点webmvcconfigurer允许开发者在一个或多个配置类中集中管理mvc配置,这有助于保持配置的一致性和可维护性。而不是分散在多个地方(如xml配置、注解配置等)。
  2. 保持与spring boot的自动配置协同工作:通过实现webmvcconfigurer接口,我们可以自定义mvc配置,而不会完全覆盖spring boot的自动配置。这是因为spring boot的webmvcautoconfiguration类已经提供了默认的mvc配置,并且它使用webmvcconfigurer来允许自定义。这种方式遵循了“约定优于配置”的原则,同时提供了灵活性。
  3. 支持多种自定义场景webmvcconfigurer提供了多个方法,覆盖了mvc的各个方面,包括拦截器、资源处理、跨域、视图控制器、消息转换器等。这意味着开发者可以在不破坏原有框架结构的情况下,针对特定需求进行定制。
  4. 促进模块化配置:通过实现webmvcconfigurer,我们可以创建多个配置类,每个配置类负责一个特定的功能模块(例如,安全模块、api模块、视图模块等)。这种模块化的配置方式使得应用更容易扩展和维护。
  5. 便于测试和调试:由于配置是集中且明确的,因此可以更容易地编写测试来验证配置是否正确,并且在调试时可以快速定位问题。
  6. 适应现代web开发需求:现代web应用通常需要处理静态资源、跨域请求、异步处理、内容协商等。webmvcconfigurer提供了对应的方法来配置这些特性,使应用能够满足现代web标准。

springboot整合拦截器interceptor

整合步骤

  1. 创建springboot项目,选择导入spring-boot-starter-web场景启动器。
  2. 编写控制器usercontroller
  3. 创建一个拦截器userinterceptor实现handlerinterceptor接口。
public class userinterceptor implements handlerinterceptor {
    @override
    public boolean prehandle(httpservletrequest request, httpservletresponse response, object handler) throws exception {
        system.out.println("拦截器 = prehandle");
        return true;
    }
    @override
    public void posthandle(httpservletrequest request, httpservletresponse response, object handler, modelandview modelandview) throws exception {
        system.out.println("拦截器 = posthandle");
    }
    @override
    public void aftercompletion(httpservletrequest request, httpservletresponse response, object handler, exception ex) throws exception {
        system.out.println("拦截器 = aftercompletion");
    }
}
  1. 自定义spring mvc配置类,实现webmvcconfigurer接口。
  • webmvcconfigurer spring mvc 提供的一个接口,用于自定义 spring mvc 的配置。在 spring boot 中,我们可以通过实现这个接口来覆盖默认的 mvc 配置,例如添加拦截器、格式化器、视图控制器等。
@configuration
public class springmvcconfiguration implements webmvcconfigurer {
    @override
    public void addinterceptors(interceptorregistry registry) {
        registry.addinterceptor(new userinterceptor())
                .addpathpatterns("/user/**")
                .excludepathpatterns("/user/login");
    }
}
  1. 访问usercontroller控制器方法。
  • http://localhost:8080/user/info
  • 触发拦截器
拦截器 = prehandle
拦截器 = posthandle
拦截器 = aftercompletion

springboot外部配置

spring boot的外部配置是指从应用代码包外部获取配置信息的机制。它允许开发者将配置信息(如数据库连接、服务器端口等)从代码中分离出来,使得应用能够在不修改源代码和重新弄编译的情况下适应不同的运行环境。

定义
外部配置:指不直接在应用代码中硬编码配置值,而是通过外部源(如配置文件、环境变量、命令行参数等)来提供配置信息,spring boot会按照预定的优先级顺序加载这些配置。

含义

外部配置的含义在于实现配置与代码的分离,它是一个分层、有序的配置加载系统,它从多个预定义的位置读取配置信息,并按照优先级顺序进行合并,高优先级的配置会覆盖低优先级的配置。使得应用具有更好的可移植性和可维护性。通过外部配置,我们可以轻松地为不同环境(开发、测试、生产)定义不同的配置,而无需修改代码。

优势

  • 灵活性:应用可以根据部署环境动态改变配置,而无需重新编译代码。
  • 安全性:敏感信息(如密码、密钥)可以不写在代码中,而是通过外部配置传入,减少泄露风险。
  • 环境适配:通过profile机制,可以轻松切换不同环境的配置。
  • 运维友好:运维人员可以通过命令行参数或环境变量快速调整配置,无需理解代码结构。
  • 云原生支持:在容器化部署(如docker)和云平台(如kubernetes)中,外部配置是标准做法,可以方便地通过环境变量或配置映射来注入配置。

spring boot 的外部配置是一个开放体系:

  • 有固定的:spring boot 核心框架提供的标准配置
  • 有扩展的:各种 starter 提供的领域特定配置(mybatis-spring-boot-starter)
  • 有自定义的:开发者根据业务需求定义的任意配置

外部配置源
spring boot 可以以下面这些方式加载外部配置,优先级从高到低(高优先级配置会覆盖低优先级配置):

  1. 命令行参数:通过java -jar命令传递的参数,例如:java -jar app.jar --server.port=8081
  2. java系统属性:使用system.getproperties()获取的属性
  3. 操作系统环境变量
  4. 从jar包外部的配置文件:例如,在jar包同一目录下的application-{profile}.propertiesapplication-{profile}.yml文件
  5. 从jar包内部的配置文件:打包在jar包内的application-{profile}.propertiesapplication-{profile}.yml文件
  6. 默认配置:通过springapplication.setdefaultproperties设置的默认属性

此外,spring boot 还支持通过@propertysource注解加载自定义的配置文件,但注意这个注解不会加载application.properties文件,而是加载指定的其他文件。

配置文件的加载位置
spring boot 会从以下位置加载application.propertiesapplication.yml文件:

  1. 当前目录的/config子目录
  2. 当前目录
  3. classpath下的/config
  4. classpath根目录

这些位置按优先级从高到低排列,高位置的配置会覆盖低位置的配置。

  • application.properties配置文件的优先级高于application.yml

功能配置

springboot:配置端口和项目根路径

server:
  port: 8080
  servlet:
    context-path: /demo

springboot:多环境profile配置和切换

spring boot 多环境配置允许我们为不同的环境(如开发、测试、生产)定义不同的配置。

我们可以通过配置文件(如application-{profile}.propertiesapplication-{profile}.yml)来指定不同环境的配置,然后通过激活不同的profile来切换环境。

除了主配置文件application.properties,还可以使用命名约定为application-{profile}.properties的配置文件。其中{profile}是激活的配置文件名称。例如,application-dev.properties用于开发环境,application-prod.properties用于生产环境。

可以通过多种方式设置激活的profile,例如在配置文件中设置spring.profiles.active=dev,或者通过命令行参数--spring.profiles.active=dev

多环境配置的主要步骤:

  1. 创建多个配置文件,分别对应不同的环境,例如:
src/main/resources/
├── application.yml           # 主配置文件,公共配置
├── application-dev.yml       # 开发环境配置
├── application-test.yml      # 测试环境配置
├── application-prod.yml      # 生产环境配置
└── application-staging.yml   # 预生产环境配置
  1. 在主配置文件application.yml中指定当前激活的环境,或者通过其他方式(如命令行参数、环境变量)来设置激活的环境。
  • 主环境配置:默认激活开发环境
# 默认激活开发环境
spring:
  profiles:
    active: dev
  • 开发环境配置:application-dev.yml
# 开发环境配置:8080端口
server:
  port: 8080
  servlet:
    context-path: /
  • 生产环境配置:application-prod.yml
# 生产环境配置:80端口
server:
  port: 80
  servlet:
    context-path: /
  • 若同时激活dev和prod环境,则后激活的配置会覆盖前面具有相同的配置。
  • 主配置文件依然可以声明key!不受环境影响,如果相同,被激活的覆盖主配置文件。
  • 在主配置文件中激活,属于静态激活。
spring:
  profiles:
    active: dev,prod
  • 运行项目包的时候动态激活。
java -jar -dspring.profiles.active=dev xxxxx.jar 

自定义配置

spring注解读取配置文件

注意事项:

  • spring框架@propertysource 默认只支持 .properties 文件,不支持 .yaml.yml 文件。
  • 若一定要使用@propertysource来读取yaml,则需要我们去配置一个propertysourcefactory工厂类,实现yaml解析。
  • 推荐使用springboot中支持yaml文件解析的configurationproperties()注解。
@data
@component
@propertysource(value = "classpath:animal.properties")
public class animal {
    @value("${animal.dog.name}")
    private string name;
    @value("${animal.dog.age}")
    private integer age;
    @value("${animal.dog.color}")
    private string color;
    @value("${animal.dog.type}")
    private string type;
}
  • animal.properties配置文件:
animal.dog.name=small yellow
animal.dog.age=18
animal.dog.color=black
animal.dog.type=中华田园犬

springboot注解批量读取配置文件

spring boot 允许将配置文件中的属性绑定到java对象上,通常使用@configurationproperties注解。

@configurationproperties批量的配置参数读取:

  • 最后一层和属性名相同,则自动映射。
  • 配置文件中的key与对象属性要一一对应。
  • 类上的配置注解:@configurationproperties(prefix = "animal.dog")前缀要精确
  • 属性和key多写或者少写都没有关系,没有则被赋值为null。

application.yaml配置文件:

animal:
  dog:
    name: 狗
    age: 18
    color: 黑
    type: 土狗

配置类:

@data
@configurationproperties(prefix = "animal.dog")  
public class dog {
    private string name;
    private integer age;
    private string color;
    private string type;
}
  • 该代码会报错,因为缺少注册机制,spring 找不到它
解决方案

方案1:使用 @enableconfigurationproperties(推荐)

  • 在主应用类或配置类上添加 @enableconfigurationproperties
@springbootapplication
@enableconfigurationproperties(value = {dog.class}) // 明确注册 dog 类
public class application {
    public static void main(string[] args) {
        springapplication.run(application.class, args);
    }
}

方案2:添加 @component 注解

  • dog 类上添加 @component 注解,让 spring 自动扫描:
@data
@component  // 添加组件注解
@configurationproperties(prefix = "animal.dog")
public class dog {
    private string name;
    private integer age;
    private string color;
    private string type;
}

方案3:使用 @configurationpropertiesscan

在主应用类上添加 @configurationpropertiesscan

@springbootapplication
@configurationpropertiesscan  // 扫描所有 @configurationproperties 类
public class application {
    public static void main(string[] args) {
        springapplication.run(application.class, args);
    }
}
// 或者指定扫描包
@springbootapplication
@configurationpropertiesscan("com.example.config")  // 指定包路径
public class application {
    // ...
}

方案4:在配置类中注册

  • 创建一个配置类来注册配置属性:
@configuration
public class appconfig {
    @bean
    @configurationproperties(prefix = "animal.dog")
    public dog dog() {
        return new dog();
    }
}

springboot测试环境

springboot的测试注解@springboottest,会自动读取启动类。

  • 测试类应该在启动类所在的包或者子包
  • 测试类不在启动类相同包或子包。
  • 自己通过注解指定启动类!@springboottest(classes = xxxxapplication.class)

导入test场景启动器:

 <dependency>
     <groupid>org.springframework.boot</groupid>
     <artifactid>spring-boot-starter-test</artifactid>
     <scope>test</scope>
 </dependency>

方式一:测试类在启动类所在包

  • 项目启动器类包路径:src/main/java/com/animal/animalapplication.java
  • 测试类包路径: src/test/java/com/animal/animalapplicationtests.java
  • 测试类与启动器类相同路径:/java/com/animal/
package com.animal;
@springboottest
class animalapplicationtests {
    @autowired
    animal animal;
    @test
    void contextloads() {
        system.out.println("animal = " + animal);
    }
}

方式二:测试类通过注解指定启动类

  • 项目启动器类包路径:src/main/java/com/animal/animalapplication.java
  • 测试类包路径: src/test/java/testdemo.java
  • 测试类不在启动器类所在包或子包下。
  • 通过注解指定启动器类,来启动测试环境。
@springboottest(classes = animalapplication.class)
public class testdemo {
    @autowired
    animal animal;
    @test
    void test(){
        system.out.println("animal = " + animal);
    }
}

其他扩展

项目父依赖spring-boot-starter-parent必须要引用吗?不引用可以使用springboot项目吗?

直接答案:不是必须的!

专业定义spring-boot-starter-parent是一个maven父pom(project object model),它提供了spring boot项目的默认配置依赖管理插件配置。使用它是可选的,但强烈推荐

spring boot 给了我们选择的自由。你可以:

1. 选择:spring-boot-starter-parent- 省心省力

    <parent>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-parent</artifactid>
        <version>3.5.6</version>
    </parent>
<project xmlns="http://maven.apache.org/pom/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
         xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelversion>4.0.0</modelversion>
    <groupid>com.cat.ssm</groupid>
    <artifactid>cat-ssm</artifactid>
    <version>1.0-snapshot</version>
    <parent>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-parent</artifactid>
        <version>3.5.6</version>
    </parent>
    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceencoding>utf-8</project.build.sourceencoding>
    </properties>
    <dependencies>
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-web</artifactid>
        </dependency>
    </dependencies>
</project>

spring-boot-starter-parent专业特性

  • 依赖管理(dependency management):统一管理所有spring boot相关依赖的版本
  • 插件配置(plugin configuration):预配置maven插件,如spring-boot-maven-plugin
  • 资源过滤(resource filtering):自动处理配置文件中的占位符替换
  • 属性配置(property configuration):预定义java版本、编码等构建属性

spring-boot-starter-parent优势:

  • 开箱即用:不用操心版本兼容
  • 配置齐全:插件、编码、java版本都配好了
  • 社区标准:遵循spring boot官方最佳实践
  • 减少错误:避免手动配置出错

2. 选择:依赖管理导入 - 自由设计,个性定制

    <dependencymanagement>
        <dependencies>
            <dependency>
                <groupid>org.springframework.boot</groupid>
                <artifactid>spring-boot-dependencies</artifactid>
                <version>${spring.boot.dependencies}</version>
            </dependency>
        </dependencies>
    </dependencymanagement>
  • 父项目pom文件
<?xml version="1.0" encoding="utf-8"?>
<project xmlns="http://maven.apache.org/pom/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
         xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelversion>4.0.0</modelversion>
    <groupid>com.sb.ssm</groupid>
    <artifactid>spring-boot-framework</artifactid>
    <version>1.0-snapshot</version>
    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceencoding>utf-8</project.build.sourceencoding>
        <spring.boot.dependencies>3.5.6</spring.boot.dependencies>
    </properties>
    <!--依赖管理-->
    <dependencymanagement>
        <dependencies>
            <dependency>
                <groupid>org.springframework.boot</groupid>
                <artifactid>spring-boot-dependencies</artifactid>
                <version>${spring.boot.dependencies}</version>
            </dependency>
            <dependency>
                <groupid>org.springframework.boot</groupid>
                <artifactid>spring-boot-starter-web</artifactid>
                <version>${spring.boot.dependencies}</version>
            </dependency>
        </dependencies>
    </dependencymanagement>
    <!--子项目-->
    <modules>
        <module>cat-ssm</module>
    </modules>
    <!-- 构建配置 -->
    <build>
        <plugins>
            <!-- 必须手动配置所有插件 -->
            <plugin>
                <groupid>org.springframework.boot</groupid>
                <artifactid>spring-boot-maven-plugin</artifactid>
            </plugin>
        </plugins>
    </build>
</project>
  • 子项目pom文件
<?xml version="1.0" encoding="utf-8"?>
<project xmlns="http://maven.apache.org/pom/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
         xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelversion>4.0.0</modelversion>
    <groupid>com.cat.ssm</groupid>
    <artifactid>cat-ssm</artifactid>
    <version>1.0-snapshot</version>
    <parent>
        <groupid>com.sb.ssm</groupid>
        <artifactid>spring-boot-framework</artifactid>
        <version>1.0-snapshot</version>
    </parent>
    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceencoding>utf-8</project.build.sourceencoding>
    </properties>
    <dependencies>
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-web</artifactid>
        </dependency>
    </dependencies>
</project>

专业特性

  • bom导入(bill of materials):通过spring-boot-dependencies导入依赖版本管理
  • 插件管理(plugin management):手动配置所有需要的maven插件
  • 自定义属性:完全控制构建环境和配置参数

dependencies的优势:

  • 完全控制:自己决定所有配置
  • 已有项目集成:已有父项目的可以无缝接入
  • 企业规范:符合公司内部的maven规范
  • 灵活定制:可以混合其他技术栈

对于大多数 spring boot 项目,继承 spring-boot-starter-parent 是最简单、最安全的选择。

  • 只有在有特殊需求或企业规范约束时,才考虑使用依赖管理导入的方式

认识springbootapplication启动器类

@springbootapplication 注解中,这三个注解的组合使得 spring boot 应用能够:

  1. 通过 @springbootconfiguration 标记主配置类,定义 bean。标记类为配置类,是 @configuration 的特殊形式。
  2. 通过 @componentscan 扫描组件,注册 bean。
  3. 通过 @enableautoconfiguration 根据条件自动配置 bean。启用自动配置,根据 classpath 和已有配置自动配置 spring 应用。

它们的执行顺序大致为:

  1. 首先,@componentscan 扫描并注册当前包及其子包下的组件。
  2. 然后,@enableautoconfiguration 根据条件自动配置其他 bean。

这种协同工作使得 spring boot 应用能够快速启动并运行,同时提供了极大的灵活性。

@springbootapplication启动器注解说明

@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 {

}
@springbootconfiguration注解

详细解释:
@springbootconfiguration 是一个类级别的注解,它表明该类是一个配置类,并且是 spring boot 应用的配置类。

  • 实际上,它是对 @configuration 注解的封装,两者在功能上是一样的。
  • 但是,@springbootconfiguration 被设计为 spring boot 应用的主配置类,通常与 @enableautoconfiguration@componentscan 结合使用,形成 @springbootapplication 注解。

关键点:

  • 它是一个特化的 @configuration,用于 spring boot 应用。
  • 它允许 spring 容器通过调用同一配置类中的 @bean 方法来管理 bean 的依赖关系,因为默认情况下(proxybeanmethods = true)会使用 cglib 代理来拦截对 @bean 方法的调用,确保返回的是 spring 容器中管理的单例 bean。
  • 在大多数情况下,一个 spring boot 应用只有一个类被标注为 @springbootconfiguration,通常就是主启动类。

示例代码:

@springbootconfiguration
public class appconfig {
    @bean
    public myservice myservice() {
        return new myserviceimpl();
    }
    @bean
    public myrepository myrepository() {
        return new myrepositoryimpl();
    }
}
@enableautoconfiguration

详细解释:
@enableautoconfiguration 是 spring boot 自动配置的核心注解。它通过 @import 导入了 autoconfigurationimportselector,这个类会利用 spring 的 springfactoriesloader 机制从 classpath 下的 meta-inf/spring.factories 文件中读取所有配置的自动配置类,然后根据条件注解(如 @conditionalonclass@conditionalonbean 等)来决定是否启用这些自动配置类。

关键点:

  • 自动配置类通常是一个 @configuration 类,但是它们只有在满足特定条件时才会被加载。
  • 自动配置的顺序可以通过 @autoconfigureorder@autoconfigurebefore@autoconfigureafter 来调整。
  • 我们可以通过 excludeexcludename 属性来排除不需要的自动配置类,也可以通过配置属性 spring.autoconfigure.exclude 来排除。

自动配置过程:

  1. 收集自动配置类autoconfigurationimportselector 使用 springfactoriesloadermeta-inf/spring.factories 中加载 enableautoconfiguration 对应的配置类列表。
  2. 过滤自动配置类:通过条件注解(如 @conditionalonclass@conditionalonbean 等)过滤掉不满足条件的配置类。
  3. 应用自动配置:将过滤后的自动配置类加载到 spring 容器中。

示例说明

假设我们有一个自动配置类用于配置数据源:

@configuration
@conditionalonclass(datasource.class)
@conditionalonproperty(name = "spring.datasource.url")
//自动配置排序
@autoconfigureorder(ordered.highest_precedence)
public class datasourceautoconfiguration {
    @bean
    @conditionalonmissingbean
    public datasource datasource(datasourceproperties properties) {
        return properties.initializedatasourcebuilder().build();
    }
}

这个自动配置类只有在 classpath 下存在 datasource 类并且配置了 spring.datasource.url 属性时才会生效,而且只有在容器中没有 datasource bean 时才会创建。

@componentscan注解

详细解释:
@componentscan 注解用于告诉 spring 扫描指定包(及其子包)下的组件,包括 @component@service@repository@controller 等注解标记的类,并将它们注册为 spring bean。如果没有指定包,则默认扫描注解所在类的包及其子包。

关键点:

  • 通过 basepackagesbasepackageclasses 属性指定要扫描的包。
  • 可以使用 includefiltersexcludefilters 进行更细粒度的控制。
  • 在 spring boot 中,通常主启动类上使用了 @springbootapplication,它包含了 @componentscan,默认扫描主启动类所在包及其子包。

扫描过程:

  1. 扫描指定包:根据 basepackagesbasepackageclasses 确定的包路径,扫描类文件。
  2. 识别组件:通过检查类上的注解(如 @component@service 等)来识别组件。
  3. 注册 bean 定义:将识别到的组件注册到 spring 容器的 bean 定义中。

示例说明:

@componentscan(basepackages = "com.example.app", 
               excludefilters = @filter(type = filtertype.annotation, classes = controller.class))
public class appconfig {
}

这个配置类会扫描 com.example.app 包及其子包下除了被 @controller 注解的类之外的所有组件。

到此这篇关于spring boot场景启动器(starters)完全指南:从入门到精通的文章就介绍到这了,更多相关spring boot场景启动器内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com