Spring Boot常用的配置

85 阅读2分钟

搭建项目/初始化依赖选择

Spring Boot版本一般选择3以下(3以上需要17以上的JDK版本)

初始化依赖选择Lombok,Spring Web,MySql Driver和MyBatis Framework,也可以根据具体项目场景增减

配置文件使用

Spring Boot默认配置文件在src/resources/application.yaml

端口

server:
  port: 7100

数据库

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/practice?serverTimezone=GMT%2b8
    username: root
    password: 123456

mybatis/mybatis-plus

mybatis-plus:
  # XML文件映射地址
  mapper-locations: classpath:mappers/*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

多环境配置

在真实场景中,可能会把项目部署在多个环境,在SpringBoot对不同环境的变量文件命以application-xxx.yaml命名区分,例如:

  • application.yaml:默认加载的配置文件
  • application-dev.yaml:开发环境加载的配置文件
  • application-test.yaml:测试环境加载的配置文件
  • application-prod.yaml:生产环境加载的配置文件

那么要如何加载不同环境的配置文件呢?

可以在application.yaml中使用spring.profiles.active指定:

如果已经将项目编译成jar包,则可以通过传入参数指定:

java -jar ./xxx.jar --spring.profiles.active=test

可以查看启动日志获取当前启动的环境:

Mybatis-plus分页插件配置

依赖版本

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.1</version>
</dependency>

配置类

package com.blog.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@MapperScan("com.blog.mappers")
public class MybatisPlusConfig {
    /**
     * 添加分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));//如果配置多个插件,切记分页最后添加
        return interceptor;
    }
}

Swagger配置

依赖版本

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>1.9.6</version>
</dependency>

配置类

package com.blog.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.function.Predicate;

@Configuration
@EnableOpenApi
public class SwaggerConfig extends WebMvcConfigurationSupport {
    /**
     * 发现如果继承了WebMvcConfigurationSupport,则在yml中配置的相关内容会失效。 需要重新指定静态资源
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/");
        registry.addResourceHandler("swagger-ui.html", "doc.html", "index.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }

    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                // 对所有api进行监控
                .apis(RequestHandlerSelectors.any())
                //不显示错误的接口地址
                .paths(Predicate.not(PathSelectors.regex("/error.*")))
                .build();
    }

    /**
     * 创建API的基本信息,这些信息会在Swagger UI中进行显示
     * @return API的基本信息
     */
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                //标题
                .title("Blog api configuration")
                // API描述
                .description("Swagger")
                //接口的版本
                .version("1.0.0")
                .build();
    }
}

Bean Copy


import org.springframework.beans.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.stream.Collectors;

public class BeanCopy {
    public static <O, T> List<T> copyBean(List<O> originList, Class<T> targetClazz) {
        return originList.stream()
                .map(list -> {
                    try {
                        T targetLit = targetClazz.getDeclaredConstructor().newInstance();

                        BeanUtils.copyProperties(list, targetLit);

                        return targetLit;
                    } catch (InstantiationException e) {
                        throw new RuntimeException(e);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    } catch (InvocationTargetException e) {
                        throw new RuntimeException(e);
                    } catch (NoSuchMethodException e) {
                        throw new RuntimeException(e);
                    }
                }).collect(Collectors.toList());
    }
}

Mybatis XML配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xxx.xxxx">
</mapper>