使用SpringBoot

使用SpringBoot

版本对应关系:

JDK 版本 推荐的 Spring Boot 版本 备注
JDK 8 Spring Boot 2.x(如 2.7.x) Spring Boot 3.x 不支持 JDK 8。
JDK 11 Spring Boot 2.x(如 2.7.x) Spring Boot 3.x 不支持 JDK 11。
JDK 12 Spring Boot 2.2.x 或 2.3.x JDK 12 是 STS 版本,建议升级到 JDK 11 或 JDK 17。
JDK 13 Spring Boot 2.3.x JDK 13 是 STS 版本,建议升级到 JDK 11 或 JDK 17。
JDK 15 Spring Boot 2.4.x JDK 15 是 STS 版本,建议升级到 JDK 17。
JDK 16 Spring Boot 2.5.x JDK 16 是 STS 版本,建议升级到 JDK 17。
JDK 17 Spring Boot 2.7.x 或 Spring Boot 3.x JDK 17 是 LTS 版本,推荐使用。
JDK 19 Spring Boot 3.x JDK 19 是 STS 版本,建议升级到 JDK 17。

入门SpringBoot项目

手动创建SpringBoot项目

  • 创建普通Maven工程

  • 在pom.xml文件中导入依赖版本管理的父工程

    • <parent>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-parent</artifactId>
          <version>2.2.6.RELEASE</version>
      </parent>
      
  • 然后在pom.xml文件中中导入相关的起步依赖即可

    • <dependencies>
          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter</artifactId>
          </dependency>
          <!-- 如果需要 Web 支持,可以添加 spring-boot-starter-web -->
          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-web</artifactId>
          </dependency>
      </dependencies>
      
  • 完善SpringBoot的项目结构

    • 创建SpringBoot主类,添加main方法以及@SpringBootApplication注解

    • @SpringBootApplication
      public class SpringBootApplicationDemo {
          public static void main(String[] args) {
              SpringApplication.run(SpringBootApplicationDemo.class,args);
          }
      }
      
    • @SpringBootApplication 是一个组合注解,包含以下三个注解:

      • @SpringBootConfiguration:标记该类为 Spring Boot 的配置类。
      • @EnableAutoConfiguration:启用 Spring Boot 的自动配置机制。
      • @ComponentScan:自动扫描当前包及其子包中的组件(如 @Controller@Service@Repository 等)。
  • 创建Controller类即可

SpringBoot的配置文件

Spring Boot 支持以下配置文件格式:

  • .properties 文件:传统的键值对格式。

    • application.properties

    • server.port=8080
      spring.datasource.url=jdbc:mysql://localhost:3306/mydb
      spring.datasource.username=root
      spring.datasource.password=secret
      
  • .yml.yaml 文件:基于 YAML 格式,结构更清晰,适合复杂配置。

    • application.yml

    • server:
        port: 8080
      spring:
        datasource:
          url: jdbc:mysql://localhost:3306/mydb
          username: root
          password: secret
      

yml格式配置文件

基本语法:

  • 键值对

    • YAML 使用 key: value 的形式表示键值对,冒号后面必须有一个空格。

    • server:
        port: 8080
      
  • YAML 使用 - 表示列表项。

    • spring:
        profiles:
          active:
            - dev
            - test
      
  • YAML 支持多行字符串,可以使用 |>

    • |:保留换行符。

    • >:折叠换行符为空格。

    • description: |
        This is a multi-line
        string with line breaks.
      
      summary: >
        This is a multi-line
        string folded into a single line.
      
  • YAML 支持嵌套结构,通过缩进表示层级关系。

    • spring:
        datasource:
          url: jdbc:mysql://localhost:3306/mydb
          username: root
          password: secret
      
  • 可以在一个文件中定义多个配置块,用 --- 分隔。

    • server:
        port: 8080
      ---
      spring:
        profiles: dev
      server:
        port: 8081
      ---
      spring:
        profiles: prod
      server:
        port: 8082
      

注意事项:

  • 缩进:YAML 使用缩进表示层级关系,必须使用空格,不能使用 Tab。
  • 大小写敏感:YAML 是大小写敏感的,keyKey 是不同的。
  • 注释:使用 # 表示注释。
  • 多文档分隔符:使用 --- 分隔多个配置块。

Profile 特定的配置文件详解

  • Profile:Profile 是 Spring Boot 中用于区分不同环境的标识符。例如,dev 表示开发环境,prod 表示生产环境。
  • Profile 特定的配置文件:文件名格式为 application-{profile}.ymlapplication-{profile}.properties,其中 {profile} 是 Profile 名称。
  • 简化部署:通过激活不同的 Profile,可以轻松切换应用的运行环境。

Profile 特定的配置文件的命名规则为:

  • YAML 文件application-{profile}.yml
  • Properties 文件application-{profile}.properties
  • 其中,{profile} 是 Profile 名称,例如 devtestprod 等。

创建不同的yml配置文件表示不同的开发环境:

  • src/main/resources 目录下创建 Profile 特定的配置文件,例如:

    • application-dev.yml(开发环境)
    • application-prod.yml(生产环境)
  • 激活不同的Profile:

    • application.ymlapplication.properties 中指定

    • spring:
        profiles:
          active: dev
      
    • 通过命令行参数指定

    • java -jar myapp.jar --spring.profiles.active=prod
      
    • 通过环境变量指定

    • export SPRING_PROFILES_ACTIVE=prod
      
  • Spring Boot 支持同时激活多个 Profile,配置项会按 Profile 的激活顺序加载,后加载的配置会覆盖前面的配置。

    • spring:
        profiles:
          active: dev,test
      

分组:

  • 使用spring.profiles.group来定义分组信息,指定每个组内有什么环境

    • spring:
        profiles:
          group:
            dev-full: dev,db-mysql,cache-redis
            prod-full: prod,db-oracle,cache-memcached
      
    • 其中dev-full组内包括dev,db-mysql,cache-redis这三个组别

  • 激活某个分组

    • 激活 Profile 分组的方式与激活单个 Profile 的方式相同。

    • application.propertiesapplication.yml 中指定激活的分组。

    • spring:
        profiles:
          active: dev-full
      
  • 这些分组的名称都对应application-分组名称.yml文件

  • 当激活一个 Profile 分组时,Spring Boot 会按照以下顺序加载配置:

    • 默认配置(application.propertiesapplication.yml)。
    • 分组中每个 Profile 的配置,按照定义的顺序加载。
    • 例如,如果激活 dev-full 分组(dev,db-mysql,cache-redis),Spring Boot 会依次加载:
      • application-dev.properties
      • application-db-mysql.properties
      • application-cache-redis.properties
    • 如果有冲突的属性,后加载的 Profile 会覆盖前面的。

SpringBoot读取配置文件信息

默认读取

  • Spring Boot 默认加载以下配置文件:

    • application.ymlapplication.properties:位于 src/main/resources 目录下。
    • Profile 特定的配置文件:如 application-dev.ymlapplication-prod.properties
    • 这些文件会被自动加载,无需额外配置。
    • application.yml 后加载,它的配置会覆盖 application.properties 中的配置,如果存在相同配置的话
  • 获取这些配置文件中的信息

    • 使用@Value注解

      • @Value 注解可以直接将配置文件中的属性值注入到字段中。

      • 属性值的格式为 ${property.name}

      • 配置文件(application.yml

        • app:
            name: MyApp
            version: 1.0.0
          
      • 获取值

        • import org.springframework.beans.factory.annotation.Value;
          import org.springframework.stereotype.Component;
          
          @Component
          public class AppConfig {
          
              @Value("${app.name}")
              private String name;
          
              @Value("${app.version}")
              private String version;
          
              public void printConfig() {
                  System.out.println("App Name: " + name);
                  System.out.println("App Version: " + version);
              }
          }
          
    • 使用 @ConfigurationProperties 注解

      • 该注解可以指定绑定前缀,并将该前缀下的属性自动绑定到一个 Java 对象中对应的字段上。

      • 注意一定要有setter方法,没有绑定不了

      • import org.springframework.boot.context.properties.ConfigurationProperties;
        import org.springframework.stereotype.Component;
        
        @Component
        @ConfigurationProperties(prefix = "app")
        public class AppConfig {
            private String name;
            private String version;
        
            // Getters and Setters
        
            public void printConfig() {
                System.out.println("App Name: " + name);
                System.out.println("App Version: " + version);
            }
        }
        

读取自定义配置文件

  • 使用 @PropertySource 注解加载自定义配置文件

    • 自定义配置文件(jdbc.properties

      • jdbc.url=jdbc:mysql://localhost:3306/mydb
        jdbc.username=root
        jdbc.password=secret
        
    • 读取java类

      • import org.springframework.beans.factory.annotation.Value;
        import org.springframework.context.annotation.Configuration;
        import org.springframework.context.annotation.PropertySource;
        
        @Configuration
        @PropertySource("classpath:jdbc.properties")
        public class JdbcConfig {
        
            @Value("${jdbc.url}")
            private String url;
        
            @Value("${jdbc.username}")
            private String username;
        
            @Value("${jdbc.password}")
            private String password;
        
            public void printConfig() {
                System.out.println("JDBC URL: " + url);
                System.out.println("JDBC Username: " + username);
                System.out.println("JDBC Password: " + password);
            }
        }
        
  • @ConfigurationProperties@PropertySource 结合

    • 可以将 @ConfigurationProperties@PropertySource 结合使用,加载自定义配置文件并将属性绑定到 Java 对象中。

    • 自定义配置文件(jdbc.yml

      • jdbc:
          url: jdbc:mysql://localhost:3306/mydb
          username: root
          password: secret
        
    • 绑定属性

      • import org.springframework.boot.context.properties.ConfigurationProperties;
        import org.springframework.context.annotation.Configuration;
        import org.springframework.context.annotation.PropertySource;
        
        @Configuration
        @PropertySource("classpath:jdbc.yml")
        @ConfigurationProperties(prefix = "jdbc")
        public class JdbcConfig {
            private String url;
            private String username;
            private String password;
        
            // Getters and Setters
        
            public void printConfig() {
                System.out.println("JDBC URL: " + url);
                System.out.println("JDBC Username: " + username);
                System.out.println("JDBC Password: " + password);
            }
        }
        

SpringBoot注册Bean

  • 使用 @Bean 注解

    • @Bean 注解用于在配置类中显式定义一个 Bean。通常用于注册第三方库的类或需要自定义初始化的 Bean。

    • @Configuration // 标记为配置类
      public class AppConfig {
      
          @Bean // 注册一个 Bean
          public UserService userService() {
              return new UserService();
          }
      }
      
    • @Bean 注解的方法返回值会被注册为 Spring Bean。

    • 方法名默认作为 Bean 的名称,也可以通过 @Bean(name = "myBean") 指定名称。

  • 使用 @Import 注解

    • @Import 注解用于将其他配置类中的 Bean 导入到当前 Spring 容器中。

    • @Import 注解可以导入其他配置类或普通的 Bean 类。

    • 适合将多个配置类组合在一起。

    • @Configuration
      @Import(OtherConfig.class) // 导入 OtherConfig 类中的 Bean
      public class AppConfig {
      }
      
  • 导入 ImportSelector 实现类

    • ImportSelector 是一个接口,用于动态选择需要导入的配置类或 Bean 类。

    • public class MyImportSelector implements ImportSelector {
          @Override
          public String[] selectImports(AnnotationMetadata importingClassMetadata) {
              return new String[]{
                  "com.example.config.AppConfig1", // 导入 AppConfig1
                  "com.example.config.AppConfig2"  // 导入 AppConfig2
              };
          }
      }
      
    • 使用 @Import 导入 ImportSelector

      • import org.springframework.context.annotation.Configuration;
        import org.springframework.context.annotation.Import;
        
        @Configuration
        @Import(MyImportSelector.class) // 导入 MyImportSelector
        public class AppConfig {
        }
        

Bean注册条件:

  • 条件注册是指根据特定条件决定是否注册某个 Bean 或配置类。
  • 通过条件注解,可以实现灵活的 Bean 注册逻辑,避免不必要的 Bean 加载。
  • 条件注解用于在满足特定条件时,才注册某个 Bean 或配置类。常见的条件包括:
    • 配置文件中的属性值
    • 类路径中是否存在某个类
    • 容器中是否已存在某个 Bean

使用示例:

  • @ConditionalOnProperty

    • 根据配置文件中的属性值决定是否注册 Bean。

    • import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      
      @Configuration
      public class AppConfig {
      
          @Bean
          @ConditionalOnProperty(name = "feature.enabled", havingValue = "true") // 当 feature.enabled=true 时注册 Bean
          public FeatureService featureService() {
              return new FeatureService();
          }
      }
      
  • @ConditionalOnClass

    • 当类路径中存在指定类时,才注册 Bean。

    • import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      
      @Configuration
      public class AppConfig {
      
          @Bean
          @ConditionalOnClass(name = "com.example.ThirdPartyClass") // 当类路径中存在 ThirdPartyClass 时注册 Bean
          public ThirdPartyService thirdPartyService() {
              return new ThirdPartyService();
          }
      }
      
  • @ConditionalOnMissingBean

    • 当容器中不存在指定 Bean 时,才注册 Bean。

    • import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      
      @Configuration
      public class AppConfig {
      
          @Bean
          @ConditionalOnMissingBean // 当容器中不存在 DataSource 时注册 Bean
          public DataSource dataSource() {
              return new DefaultDataSource();
          }
      }
      

SpringBoot设置拦截器

  • 在请求到达具体的控制器方法之前,拦截器的preHandle方法会被调用。可以在这里执行一些预处理逻辑,例如权限验证、日志记录等。
  • 如果preHandle返回true,请求会继续传递到下一个拦截器或控制器;如果返回false,请求会被中断。
  • 如果所有拦截器的preHandle方法都返回true,请求会到达目标控制器方法。

配置步骤:

  • SpringBoot中拦截器的配置方式和SpringMVC中拦截器配置方式基本相同

  • 首先创建一个拦截器类并实现HandlerInterceptor接口,并重写其中的方法:

    • public class UserInterceptor implements HandlerInterceptor {
          @Override
          public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
              System.out.println("拦截器执行了");
              return true;
          }
      
          @Override
          public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
      
          }
      
          @Override
          public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
      
          }
      
  • 然后通过通过实现WebMvcConfigurer接口,将拦截器注册到Spring Boot应用中:

    • @Configuration
      public class WebConfig implements WebMvcConfigurer {
      
          @Autowired
          private MyInterceptor myInterceptor;
      
          @Override
          public void addInterceptors(InterceptorRegistry registry) {
              // 注册拦截器,并指定拦截的路径
              registry.addInterceptor(myInterceptor)
                      .addPathPatterns("/**") // 拦截所有路径
                      .excludePathPatterns("/public/**"); // 排除特定路径
          }
      }
      
  • 如果不想实现WebMvcConfigurer接口,可以直接在配置类中通过@Bean注册拦截器。

    • 使用@Bean注册拦截器可以使用条件注解进行判断,根据配置文件动态启用或禁用拦截器

    • @Configuration
      public class WebConfig {
      
          @Bean
          @ConditionalOnProperty(name = "interceptor.enabled", havingValue = "true", matchIfMissing = true)
          public WebMvcConfigurer webMvcConfigurer() {
              return new WebMvcConfigurer() {
                  @Override
                  public void addInterceptors(InterceptorRegistry registry) {
                      registry.addInterceptor(new MyInterceptor())
                              .addPathPatterns("/**")
                              .excludePathPatterns("/public/**");
                  }
              };
          }
      }
      

拦截器的执行顺序

  • 如果有多个拦截器,它们的执行顺序如下:

    • 按照注册顺序依次执行preHandle方法。

    • 控制器方法执行。

    • 按照注册顺序的逆序依次执行postHandle方法。

    • 按照注册顺序的逆序依次执行afterCompletion方法。

    • @Override
      public void addInterceptors(InterceptorRegistry registry) {
          registry.addInterceptor(interceptor1);
          registry.addInterceptor(interceptor2);
      }
      

SpringBoot整合Mybatis

连接数据库

导入相关依赖:

  • mybatis的起步依赖

    • Spring Boot 提供了 MyBatis-Spring-Boot-Starter,它会自动配置 MyBatis 的相关组件,包括:
      • 自动扫描主启动类所在的包或其子包下的 Mapper 接口。
      • 如果 Mapper 接口不在主启动类所在的包或其子包下,可能需要手动指定扫描路径。
      • 自动配置 SqlSessionFactorySqlSessionTemplate
      • 自动注入数据源。
  • mysql数据库驱动依赖

  • <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.4</version>
    </dependency>
    
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.33</version>
        <scope>runtime</scope>
    </dependency>
    
  • 在默认的配置文件中配置数据库信息,SpringBoot会自动读取这些配置文件

    • 例如在application.yml文件中配置

    • spring:
        datasource:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3306/learn
          username: root
          password: root
      
  • 编写mapper接口实现数据库操作,注意在mapper接口上添加@Mapper注解

    • @Mapper
      public interface UserMapper {
          @Select("SELECT * FROM user WHERE id = #{id}")
          User findById(Long id);
      }
      
  • 在服务类中自动注入UserMapper接口调用方法即可

  • 开启驼峰命名自动映射

    • MyBatis 提供了一个全局配置项 mapUnderscoreToCamelCase,可以将数据库中的下划线命名法(user_address)自动映射为 Java 实体类的驼峰命名法(userAddress)。

    • application.propertiesapplication.yml 中添加以下配置:

    • mybatis:
        configuration:
          map-underscore-to-camel-case: true
      

配置数据库连接池

默认连接池:

  • com.zaxxer.hikari.HikariDataSource
  • 默认的连接池为 Hikari,Hikari是性能最好的连接池,也是springboot推荐的连接池,但除了Hikari还有一个经常用的Druid连接池

手动指定连接池:

  • 导入Druid数据库连接池或者其他连接池依赖

    • <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>druid-spring-boot-starter</artifactId>
          <version>1.2.16</version>
      </dependency>
      
    • 添加完该依赖后SpringBoot就自动使用Druid连接池了,如果手动指定连接池的话要添加配置:

    • spring:
        datasource:
      #    type: com.alibaba.druid.pool.DruidDataSource
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3306/learn
          username: root
          password: root
      

事务管理

  • Spring Boot默认已经启用了事务管理,只需要在需要事务管理的方法或类上添加@Transactional注解即可。

  • Spring Boot通过spring-boot-autoconfigure模块提供了大量的自动配置类。对于事务管理,Spring Boot会自动配置DataSourceTransactionManager,这是Spring用于管理JDBC事务的核心组件。

    • DataSourceTransactionManager:Spring Boot会自动检测到DataSource的存在,并为其配置一个DataSourceTransactionManager
    • @EnableTransactionManagement:Spring Boot的自动配置已经默认启用了事务管理,因此不需要手动添加@EnableTransactionManagement注解。
  • @Transactional注解可以应用于类或方法上:

    • 应用于类上:表示该类的所有方法都启用事务管理。

    • 应用于方法上:表示该方法启用事务管理。

    • @Transactional
      @RequestMapping("/user")
      public String user(){
          int num=0;
          userServer.insertUser();
          System.out.println(1/num);
          userServer.deleteUser();
          return "OK";
      }
      

SpringBoot全局异常处理器

  • 在Spring Boot应用中,全局异常处理器(Global Exception Handler)用于集中处理应用中抛出的异常,避免在每个Controller中重复编写异常处理逻辑。通过全局异常处理器,可以统一处理异常并返回一致的错误响应。

  • 使用 @ControllerAdvice@ExceptionHandler

  • Spring Boot 提供了 @ControllerAdvice@ExceptionHandler 注解来实现全局异常处理。

    • @ControllerAdvice:用于定义全局异常处理类,可以应用到所有的Controller。
      • @RestControllerAdvice仅作用于 @RestController 注解的控制器,自动添加 @ResponseBody,返回值直接作为响应体
    • @ExceptionHandler:用于定义处理特定异常的方法。
    @RestControllerAdvice
    public class UserExceptionHandler   {
    
        @ExceptionHandler(ConstraintViolationException.class)
        public Result handlerException(ConstraintViolationException ex){
            //在日志中记录异常信息
            //处理异常返回结果
            return Result.error("参数错误");
    
        }
    }
    

SpringBoot参数校验

基本介绍

作用:

  • 确保客户端传递的数据符合业务规则。
  • 防止非法数据进入系统,提高系统的健壮性。
  • 减少手动校验代码,提高开发效率。

常见场景:

  • 字段不能为空。
  • 字符串长度限制。
  • 数字范围限制。
  • 正则表达式匹配。
  • 自定义校验规则。

导入依赖:

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

常用的校验注解

注解 作用
@NotNull 字段不能为null
@NotEmpty 字段不能为null或空字符串(适用于字符串、集合等)。
@NotBlank 字段不能为null,且至少包含一个非空白字符。
@Size 字段的长度或大小必须在指定范围内(适用于字符串、集合等)。
@Min 字段的最小值。
@Max 字段的最大值。
@Email 字段必须是合法的电子邮件地址。
@Pattern 字段必须匹配指定的正则表达式。
@Positive 字段必须是正数。
@Negative 字段必须是负数。
@Future 字段必须是未来的日期。
@Past 字段必须是过去的日期。
@Valid 用于嵌套对象的校验。

使用步骤

  • 在接收参数的方法中在形参的前面使用相应的注解

  • 在使用校验注解的类上添加@Validated注解

  • @RestController
    @RequestMapping("/user")
    @Validated
    public class UserController {
        @Autowired
        UserService userService;
    
        @PostMapping("/register")
                					//用户名密码校验
        public Result registerUser(@NotNull @RequestParam("username") String username,
                                   @Pattern(regexp = "^\\S{5,16}$")
                                   @RequestParam("password") String password){
    
    

处理校验异常

  • 当参数校验失败时,Spring会抛出MethodArgumentNotValidException(对于请求体)或ConstraintViolationException(对于路径变量和请求参数)

    • 当使用@Valid注解对请求体(@RequestBody)进行校验时,如果校验失败,Spring会抛出MethodArgumentNotValidException

    • @RestController
      @RequestMapping("/users")
      public class UserController {
      
          @PostMapping
          public String createUser(@Valid @RequestBody User user) {
              return "用户创建成功";
          }
      }
      
      • @RequestBody:将 HTTP 请求体中的 JSON 数据绑定到 User 对象。

      • @Valid:启用对 User 对象的参数校验。

      • 校验的具体内容取决于 User 类中定义的校验规则。比如

      • public class User {
        
            @NotNull(message = "用户ID不能为空")
            private Long id;
        
            @NotBlank(message = "用户名不能为空")
            @Size(min = 2, max = 10, message = "用户名长度必须在2到10之间")
            private String username;
        
            @Email(message = "邮箱格式不正确")
            private String email;
        
            @Min(value = 18, message = "年龄必须大于18岁")
            @Max(value = 100, message = "年龄必须小于100岁")
            private int age;
        
            // Getter和Setter方法
        }
        
    • 当使用@Validated注解对路径变量(@PathVariable)或请求参数(@RequestParam)进行校验时,如果校验失败,Spring会抛出ConstraintViolationException

    • @RestController
      @RequestMapping("/users")
      @Validated // 启用方法级别的校验
      public class UserController {
      
          @GetMapping("/{id}")
          public String getUser(@PathVariable @Min(1) Long id) {
              return "用户ID: " + id;
          }
      
          @GetMapping("/search")
          public String searchUser(
                  @RequestParam @NotBlank String username,
                  @RequestParam @Email String email) {
              return "搜索用户: " + username + ", 邮箱: " + email;
          }
      }
      
  • 通过配置全局异常处理器来处理这些异常信息

  • @RestControllerAdvice
    public class UserExceptionHandler   {
    
        @ExceptionHandler(ConstraintViolationException.class)
        public Result handlerException(ConstraintViolationException ex){
            //在日志中记录异常信息
            //处理异常返回结果
            return Result.error("参数错误");
        }
    }
    

SpringBoot整合Junit

导入依赖:

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

编写测试类:

  • 需要在测试方法上添加@Test注解

  • 需要在测试类上声明两个注解

    • @SpringBootTest(classes = SpringBootApplicationDemo.class)
      • 用于启动 Spring Boot 应用上下文,加载所有 Bean 和配置。
    • @RunWith(SpringRunner.class)
      属于 JUnit 4,是 JUnit 4 提供的扩展机制。
    • @ExtendWith(SpringExtension.class)
      属于 JUnit 5,是 JUnit 5 提供的扩展机制。
      • 两者的核心作用相同:将 Spring 测试框架与 JUnit 集成,使得在测试中可以启动 Spring 上下文(ApplicationContext),并使用 Spring 的功能(如依赖注入、配置加载等)
  • @ExtendWith(SpringExtension.class)
    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = SpringBootApplicationDemo.class)
    public class User {
    
        @Autowired
         UserServer userServer;
    
        @Test
        public void test(){
            System.out.println(userServer.getUserById(1));
        }
    }
    

声明周期方法:

  • @BeforeEach
    • 作用:在每个测试方法执行之前运行。
  • @AfterEach
    • 作用:在每个测试方法执行之后运行。
  • @BeforeAll
    • 作用:在所有测试方法执行之前运行(静态方法)。
    • 只执行一次
  • @AfterAll
    • 作用:在所有测试方法执行之后运行(静态方法)。
    • 只执行一次

集成测试:

  • 集成测试用于测试依赖 Spring 容器的代码(如 Controller、Repository 等)。

  • 模拟浏览器发送请求

  • 相关注解和方法:

    • @AutoConfigureMockMvc:自动配置 MockMvc,用于模拟 HTTP 请求。

    • mockMvc.perform():模拟 HTTP 请求并验证响应。

    • @SpringBootTest(classes = SpringBootApplicationDemo.class)
      @AutoConfigureMockMvc
      public class UserControllerTest {
      
          @Autowired
          private MockMvc mockMvc;
      
          @Test
          public void testGreet() throws Exception {
              mockMvc.perform(get("/greet").param("name", "World"))
                     .andExpect(status().isOk())
                     .andExpect(content().string("Hello, World"));
          }
      }
      

Spring项目打包

  • 在在 pom.xml 中添加打包插件:

    • <build>
          <plugins>
              <plugin>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-maven-plugin</artifactId>
              </plugin>
          </plugins>
      </build>
      
  • 使用Maven的package命令打包为jar包

  • 使用 java -jar 命令运行jar包,注意运行该jar的环境中中要包含jre

更改配置信息:

  • 部署后的SpringBoot项目可以通过以下方式更改配置信息

    • 使用命令行参数

      • 在启动 Spring Boot 应用时,可以通过命令行参数覆盖配置属性。命令行参数以 -- 开头。

      • java -jar myapp.jar --server.port=8081 --spring.profiles.active=prod
        
        • --server.port=8081:将服务器端口设置为 8081。
        • --spring.profiles.active=prod:激活 prod 配置文件。
    • 配置环境变量

      • 可以通过配置本地环境变量信息更改配置
    • jar包所在目录下的application.yaml文件

      • 可以在当前jar包所在目录下新建application.yaml配置文件来配置相关信息
posted @ 2025-03-18 15:40  QAQ001  阅读(68)  评论(0)    收藏  举报