java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Spring Boot场景启动器

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

作者:南部余额

本文给大家介绍Spring Boot场景启动器(Starters)完全指南:从入门到精通,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

什么是场景启动器?

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

核心理念:

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

简化整合(项目依赖):

简化开发(核心组件):

简化配置(配置文件):

下面列出一些常见的Spring Boot场景启动器:

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

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

        <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底层是如何帮助我们实现的场景启动器版本管理呢?

这样的设计是为了将依赖管理(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-starter-parent 的 pom.xml,你会看到它并没有重复定义依赖版本,而是通过继承 spring-boot-dependencies 来获得所有版本管理。同时,它定义了一些其他元素,比如:

因此,当我们在项目中继承 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专业特性

spring-boot-starter-parent优势:

导入场景启动器

    <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 容器的启动过程,实现零配置或最小配置的应用启动

@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) {
    	// 启动tomcat和ioc容器
        SpringApplication.run(MainApplication.class, args);
    }
}

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

@RestController
@RequestMapping("user")
public class UserController {
    @RequestMapping("info")
    public String info(){
        return "hello";
    }
}

SpringBoot整合Spring MVC

Spring Boot 整合 Spring MVC 非常简便,因为 Spring Boot 已经为 Spring MVC 提供了自动配置。

  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. 访问控制器地址

什么是 WebMvcConfigurer?

WebMvcConfigurer 是 Spring MVC 框架中的一个核心接口,它提供了回调方法,允许开发者在 Spring 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接口。
@Configuration
public class SpringMvcConfiguration implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new UserInterceptor())
                .addPathPatterns("/user/**")
                .excludePathPatterns("/user/login");
    }
}
  1. 访问UserController控制器方法。
拦截器 = preHandle
拦截器 = postHandle
拦截器 = afterCompletion

SpringBoot外部配置

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

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

含义

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

优势

Spring Boot 的外部配置是一个开放体系:

外部配置源
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根目录

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

功能配置

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
# 开发环境配置:8080端口
server:
  port: 8080
  servlet:
    context-path: /
# 生产环境配置:80端口
server:
  port: 80
  servlet:
    context-path: /
spring:
  profiles:
    active: dev,prod
java -jar -Dspring.profiles.active=dev XXXXX.jar 

自定义配置

spring注解读取配置文件

注意事项:

@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.dog.name=small yellow
animal.dog.age=18
animal.dog.color=black
animal.dog.type=中华田园犬

SpringBoot注解批量读取配置文件

Spring Boot 允许将配置文件中的属性绑定到Java对象上,通常使用@ConfigurationProperties注解。

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

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;
}
解决方案

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

@SpringBootApplication
@EnableConfigurationProperties(value = {Dog.class}) // 明确注册 Dog 类
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

方案2:添加 @Component 注解

@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,会自动读取启动类。

导入test场景启动器:

 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-test</artifactId>
     <scope>test</scope>
 </dependency>

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

package com.animal;
@SpringBootTest
class AnimalApplicationTests {
    @Autowired
    Animal animal;
    @Test
    void contextLoads() {
        System.out.println("animal = " + animal);
    }
}

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

@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专业特性

spring-boot-starter-parent优势:

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

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring.boot.dependencies}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
<?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>
<?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>

专业特性

dependencies的优势:

对于大多数 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 应用的配置类。

关键点:

示例代码:

@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 等)来决定是否启用这些自动配置类。

关键点:

自动配置过程:

  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。如果没有指定包,则默认扫描注解所在类的包及其子包。

关键点:

扫描过程:

  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场景启动器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文