首页 > 其他分享 >04 springboot-工程搭建案例(多环境部署,数据源, Swagger, 国际化,工具类)

04 springboot-工程搭建案例(多环境部署,数据源, Swagger, 国际化,工具类)

时间:2024-10-26 10:52:42浏览次数:9  
标签:return springboot 数据源 private static Swagger cause public String

项目搭建模板(多环境切换)


springboot系列,最近持续更新中,如需要请关注

如果你觉得我分享的内容或者我的努力对你有帮助,或者你只是想表达对我的支持和鼓励,请考虑给我点赞、评论、收藏。您的鼓励是我前进的动力,让我感到非常感激。

文章目录

1 项目截图

请添加图片描述

2 pom.xml

<?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*属性表示使用的POM模型的版本。选择和你正在使用的Maven版本一致的版本即可。版本4.0.0适用于Maven 2和3 -->
    <modelVersion>4.0.0</modelVersion>

    <groupId>wyh.com</groupId>
    <artifactId>Demo_01_1_SpringBootItemDemo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <springfox.version>2.8.0</springfox.version>
    </properties>


    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <!--  Spring相关依赖【开始】-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--  Spring相关依赖【结束】-->

        <!-- 添加日志依赖【开始】 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!-- 添加日志依赖【结束】 -->


        <!-- 添加工具类【开始】 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.83</version>
        </dependency>
        <!-- 添加工具类【结束】 -->

        <!-- swagger2【开始】 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${springfox.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${springfox.version}</version>
        </dependency>
        <!-- swagger2【结束】 -->

        <!-- mysql数据 驱动【开始】 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>
        <!-- mysql数据 驱动【结束】 -->

        <!-- 整合mybatis【开始】-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.3.0</version>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.tomcat</groupId>
                    <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- 整合mybatis【结束】-->
    </dependencies>

    <!-- 多环境配置【开始】 -->
    <profiles>
        <!-- 开发环境环境 -->
        <profile>
            <id>dev</id>
            <properties>
                <package.environment>dev</package.environment>
            </properties>
            <!-- 是否默认 true表示默认-->
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>
        <!-- 测试环境 -->
        <profile>
            <id>test</id>
            <properties>
                <package.environment>test</package.environment>
            </properties>
        </profile>

        <profile>
            <!-- 生产环境 -->
            <id>prod</id>
            <properties>
                <package.environment>prod</package.environment>
            </properties>
        </profile>
    </profiles>
    <!-- 多环境配置【结束】 -->

    <build>
        <!-- 解决application.yml配置文件中@project.version@获取不到问题 -->
        <resources>
            <resource>
                <directory>${basedir}/src/main/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>application.yml</include>
                    <include>application-${package.environment}.yml</include>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>

        <!-- 解决打成的jar运行报“找不见注类”问题 -->
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>wyh.com.Demo011SpringBootItemDemoApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

3 多环境配置

application.yml

# APP版本
app:
  version: @project.version@

# 指定执行环境
spring:
  profiles:
    active: @package.environment@
  servlet:
    multipart:
      # 上传文件总的最大值
      max-file-size: 10MB
      # 单个文件的最大值
      max-request-size: 10MB


# 用户初试密码【测试代码读取静态配置时用】
user:
  password: 123456

application-dev.yml 、application-prod.yml、application-test.yml

# 服务配置
server:
  tomcat:
    uri-encoding: UTF-8
    max-threads: 1000
    min-spare-threads: 30
    # 重新设置tomcat服务器允许上传的文件的大小【默认2MB】,解决MultipartException无法捕获的问题
    max-swallow-size: -1
  port: 16001
  servlet:
    context-path: /Demo_01_1_SpringBootItemDemo
  compression:
    enabled: true
    mime-types: application/json
    min-response-size: 8192

# 日志配置
logging:
  config: classpath:logConfig/logback-dev.xml

# 数据源配置
spring:
  datasource:
    name: test
    # 代码中测试案例连接的库
    url: jdbc:mysql://localhost:3306/personal_demo?useTimezone=true&serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8
    username: root
    password: root123
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    filters: stat
    maxActive: 20
    initialSize: 1
    maxWait: 60000
    minIdle: 1
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: select 'x'
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    maxOpenPreparedStatements: 20
  # 解决数据库返回时间时区不一致导致时差问题
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8

logConfig 配置 logback-dev.xml、logback-prod.xml、logback-test.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!-- 定义日志文件 输入位置 -->
    <property name="log_dir" value="D:/00 test"/>
    <!-- 日志最大的历史 6 个月  -->
    <property name="maxHistory" value="6"/>

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{dd-MM-yyyy HH:mm:ss.SSS} %magenta([%thread]) %highlight(%-5level) %logger{36}.%M - %msg%n
            </pattern>
        </encoder>
        <target>System.out</target>
    </appender>

    <appender name="SIZEROLLFILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <encoder>
            <pattern>%d{dd-MM-yyyy HH:mm:ss.SSS} %magenta([%thread]) %highlight(%-5level) %logger{36}.%M - %msg%n
            </pattern>
        </encoder>
        <append>true</append>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <!-- 上环境时修改此路径 -->
            <fileNamePattern>${log_dir}/springboot.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <maxFileSize>10MB</maxFileSize>
            <maxHistory>${maxHistory}</maxHistory>
        </rollingPolicy>
    </appender>

    <root level="INFO">
        <appender-ref ref="CONSOLE"/>
        <!-- 输出到指定目录下-->
        <!--<appender-ref ref="SIZEROLLFILE"/>-->
    </root>

    <!-- 修改dao层的日志输出级别 -->
    <logger name="com.huawei.dao" level="DEBUG" additivity="false">
        <appender-ref ref="CONSOLE"/>
    </logger>

</configuration>

4 国际化配置文件及工具类

4.1 配置文件

messages_en_US.properties

# \u7CFB\u7EDF\u72B6\u6001\u7801 # 系统状态码 ============================================================================================================
error.20000=The request is successful.
error.40000=Param error!
error.50000=System error!

messages_zh_CN.properties

# 系统状态码 ============================================================================================================
error.20000=请求成功.
error.40000=参数错误!
error.50000=系统异常!

4.2 全局异常码

GlobalError

public enum GlobalError {
    // 系统状态码 ====================================================================================================
    SUCCESS(20000),
    PARAM_ERROR(40000),
    EXCEPTION(50000);

    int code;

    GlobalError(int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return I18nUtils.getMsgByErrorCode(code);
    }

    public String getMessageWithParams(String supplementMsg) {
        return I18nUtils.getI18nErrorMsg(code, supplementMsg, CookieUtil.getLanguage());
    }

    public String getMessageEnWithParams(String supplementMsg) {
        return I18nUtils.getI18nErrorMsg(code, supplementMsg, Constants.Other.EN);
    }

    public String getMessageCnWithParams(String supplementMsg) {
        return I18nUtils.getI18nErrorMsg(code, supplementMsg, Constants.Other.ZH);
    }
}

4.3 国际化工具类

CookieUtil

public class CookieUtil {
    private static final String ZH = "zh";
    private static final String EN = "en";
    private static final String CN = "cn";
    private static final String US = "us";
    private static final String ZH_CN = "zh_cn";
    private static final String LANG = "lang_key";

    public CookieUtil() {
    }

    public static String getLanguage() {
        return decideLocaleInfoFromCookie("en", "zh");
    }

    public static String getCountry() {
        return decideLocaleInfoFromCookie("us", "cn");
    }

    private static String decideLocaleInfoFromCookie(String defaultEnValue, String cnValue) {
        HttpServletRequest request = getRequest();
        Cookie[] cookies = null;
        if (request != null) {
            cookies = getCookies(request);
        }

        if (cookies != null) {
            Cookie[] var4 = cookies;
            int var5 = cookies.length;

            for (int var6 = 0; var6 < var5; ++var6) {
                Cookie cookie = var4[var6];
                if ("lang_key".equals(cookie.getName()) && "zh_cn".equals(cookie.getValue())) {
                    return cnValue;
                }
            }
        }

        return defaultEnValue;
    }

    public static Cookie[] getCookies(HttpServletRequest request) {
        Cookie[] cookies = null;
        if (request.getCookies() != null) {
            cookies = request.getCookies();
        } else {
            String cookieStr = request.getHeader("cookie");
            if (StringUtils.isNotBlank(cookieStr)) {
                cookies = (Cookie[]) HttpCookie.parse(cookieStr).stream().map((httpCookie) -> {
                    return new Cookie(httpCookie.getName(), httpCookie.getValue());
                }).toArray((x$0) -> {
                    return new Cookie[x$0];
                });
            }
        }

        return cookies;
    }

    public static String getCountryByLanguage(String language) {
        String country = "us";
        if ("zh".equals(language)) {
            country = "cn";
        }

        return country;
    }

    public static HttpServletRequest getRequest() {
        HttpServletRequest request = null;
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        if (attributes != null && attributes instanceof ServletRequestAttributes) {
            request = ((ServletRequestAttributes) attributes).getRequest();
        }

        return request;
    }
}

I18nUtils

@Slf4j
public class I18nUtils {

    public static String getI18nErrorMsg(int code, String supplementMsg, String language) {
        String key = "error." + code;
        String message = getMsgByLanguage(key, language);
        if (StringUtils.isNotEmpty(message)) {
            message = message + " " + supplementMsg;
        }
        return message;
    }

    private static String getMsgByLanguage(String key, String language) {
        String country = getCountryByLanguage(language);

        ResourceBundle bundle = null;
        String value = null;

        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        return getMsg(key, language, country, value, contextClassLoader);
    }

    private static String getMsg(String key, String language, String country, String value, ClassLoader contextClassLoader) {
        ResourceBundle bundle;
        try {
            if (contextClassLoader != null) {
                bundle = ResourceBundle.getBundle("i18/messages", new Locale(language, country), contextClassLoader);
            } else {
                bundle = ResourceBundle.getBundle("i18/message", new Locale(language, country));
            }

            if (bundle != null) {
                value = bundle.getString(key);
            }
        } catch (MissingResourceException var8) {
            log.error("missing resource error !");
        }

        return value;
    }


    private static String getCountryByLanguage(String language) {
        String country = "us";
        if ("zh".equals(language)) {
            country = "cn";
        }

        return country;
    }

    public static String getMsgByErrorCode(int code) {
        ClassLoader classLoader = null;
        if (code > 10000) {
            classLoader = Thread.currentThread().getContextClassLoader();
        }

        String key = "error." + code;

        String language = CookieUtil.getLanguage();

        String country = CookieUtil.getCountry();
        String value = null;

        return getMsg(key, language, country, value, classLoader);
    }
}

Constants

public interface Constants {

    /**
     * The interface Other.
     */
    interface Other {

        /**
         * The constant ZH.
         */
        String ZH = "zh";

        /**
         * The constant EN.
         */
        String EN = "en";
    }
}

4.4 使用

使用测试接口测试即可

  @ApiOperation(value = "Hello测试", notes = "无参数测试")
    @GetMapping("/testMysql")
    public RespResult testMysql(String name, Map reqParam) {
        String testStr = testService.getTestStr();
        return RespResult.resultOK(testStr);
    }

在这里插入图片描述

5 其他相关代码

5.1 主类、接口返回结果包装类

Demo011SpringBootItemDemoApplication

@SpringBootApplication
public class Demo011SpringBootItemDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(Demo011SpringBootItemDemoApplication.class, args);
    }
}

RespResult

@Data
public class RespResult {
    /**
     * The Code.
     */
    int code = RespCodeEnum.SUCCESS.getCode();

    /**
     * The Data.
     */
    Object data;

    /**
     * The Msg.
     */
    String msg;

    /**
     * 处理请求响应正常时方法
     *
     * @param data 返回的数据
     * @return RespResult 数据
     */
    public static RespResult resultOK(Object data) {
        RespResult respResult = new RespResult();
        respResult.data = data == null ? new HashMap<>() : data;
        respResult.msg = GlobalError.SUCCESS.getMessage();
        return respResult;
    }

    /**
     * 处理请求异常时方法
     *
     * @param code 状态码
     * @param msg  异常信息
     * @param data 数据
     * @return RespResult data
     */
    public static RespResult resultFail(int code, String msg, Object data) {
        RespResult respResult = new RespResult();
        respResult.code = code;
        respResult.msg = msg;
        respResult.data = data;
        return respResult;
    }

    /**
     * 处理请求异常时方法
     *
     * @param code 状态码
     * @param msg  异常信息
     * @return RespResult data
     */
    public static RespResult resultFail(int code, String msg) {
        RespResult respResult = new RespResult();
        respResult.data = new HashMap<>();
        respResult.code = code;
        respResult.msg = msg;
        return respResult;
    }
}

RespCodeEnum

/**
 * < 存放请求响应码常量>
 * <p>
 */
public enum RespCodeEnum {
    SUCCESS(200, "The request is successful.", "请求成功."),
    EXP(500, "System error! ", "系统异常!");

    private Integer code;

    private String descEn;

    private String descCn;

    RespCodeEnum(final int code, final String descEn, final String descCn) {
        this.code = code;
        this.descEn = descEn;
        this.descCn = descCn;
    }

    /**
     * <设置code值>
     *
     * @return Integer 数据
     */
    public Integer getCode() {
        return code;
    }

    /**
     * <获取导入校验枚举描述>
     *
     * @return Integer 数据
     */
    public String getDescEn() {
        return descEn;
    }

    /**
     * <获取导入校验枚举描述>
     *
     * @return Integer 数据
     */
    public String getDescCn() {
        return descCn;
    }
}

5.2 全局异常

CommonServiceException

/**
 * 自定义公共异常类
 */
@Data
public class CommonServiceException extends RuntimeException {
    private static final long serialVersionUID = -3387516993124223448L;

    private int errorCode;

    private String errorMsg;

    private String errorMsgEn;

    private String errorMsgCn;

    /**
     * Gets error code.
     *
     * @return the error code
     */
    public int getErrorCode() {
        return GlobalError.EXCEPTION.getCode() == errorCode ? RespCodeEnum.EXP.getCode() : errorCode;
    }

    /**
     * Instantiates a new Common service exception.
     */
    public CommonServiceException() {
        super();
    }

    /**
     * Instantiates a new Common service exception.
     *
     * @param msg the msg
     */
    public CommonServiceException(String msg) {
        super(msg);
        this.errorCode = RespCodeEnum.EXP.getCode();
        this.errorMsg = msg;
        this.errorMsgEn = msg;
        this.errorMsgCn = msg;
    }

    /**
     * Instantiates a new Common service exception.
     *
     * @param cause the cause
     */
    public CommonServiceException(Throwable cause) {
        super(cause);
    }

    /**
     * Instantiates a new Common service exception.
     *
     * @param globalError the ai model error
     * @param cause the cause
     */
    public CommonServiceException(GlobalError globalError, Throwable cause) {
        super(globalError.getMessageEnWithParams(null), cause);
        this.errorCode = globalError.getCode();
        this.errorMsg = globalError.getMessage();
        this.errorMsgEn = globalError.getMessageEnWithParams(null);
        this.errorMsgCn = globalError.getMessageCnWithParams(null);
    }

    /**
     * Instantiates a new Common service exception.
     *
     * @param globalError the ai model error
     */
    public CommonServiceException(GlobalError globalError) {
        super(globalError.getMessageEnWithParams(null));
        this.errorCode = globalError.getCode();
        this.errorMsg = globalError.getMessage();
        this.errorMsgEn = globalError.getMessageEnWithParams(null);
        this.errorMsgCn = globalError.getMessageCnWithParams(null);
    }

    /**
     * Instantiates a new Common service exception.
     *
     * @param globalError the ai model error
     * @param supplementMsg the supplement msg
     * @param cause the cause
     */
    public CommonServiceException(GlobalError globalError, String supplementMsg, Throwable cause) {
        super(globalError.getMessageEnWithParams(null), cause);
        this.errorCode = globalError.getCode();
        this.errorMsg = globalError.getMessageWithParams(supplementMsg);
        this.errorMsgEn = globalError.getMessageEnWithParams(supplementMsg);
        this.errorMsgCn = globalError.getMessageCnWithParams(supplementMsg);
    }

    /**
     * Instantiates a new Common service exception.
     *
     * @param globalError the ai model error
     * @param supplementMsg the supplement msg
     */
    public CommonServiceException(GlobalError globalError, String supplementMsg) {
        super(globalError.getMessageEnWithParams(null));
        this.errorCode = globalError.getCode();
        this.errorMsg = globalError.getMessageWithParams(supplementMsg);
        this.errorMsgEn = globalError.getMessageEnWithParams(supplementMsg);
        this.errorMsgCn = globalError.getMessageCnWithParams(supplementMsg);
    }
}

GlobalExceptionHandler

/**
 * 全局异常处理器
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 全局所有异常处理器
     *
     * @param exception 异常对象
     * @param request 请求对象
     * @param response 响应对象
     * @return RespResult 返回结果
     */
    @ExceptionHandler( {Exception.class, Error.class})
    @ResponseBody
    public RespResult exceptionHandler(Exception exception, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("contentType", "text/html; charset=utf-8");
        boolean isSensitiveException = isSensitiveException1(exception);
        if (isSensitiveException) {
            LOGGER.error("{} Exception: System Exception", OtherUtils.replaceCRLF(request.getRequestURI()));
            printLocalExceptionInfo(exception);
        } else {
            LOGGER.error("{} Exception: ", OtherUtils.replaceCRLF(request.getRequestURI()), exception);
        }
        if (exception instanceof ServletException) {
            ServletException exp = (ServletException) exception;
            return RespResult.resultFail(RespCodeEnum.EXP.getCode(),
                GlobalError.EXCEPTION.getMessageWithParams(exp.getLocalizedMessage()));
        }
        return RespResult.resultFail(RespCodeEnum.EXP.getCode(), GlobalError.EXCEPTION.getMessage());
    }

    /**
     * 自定义的异常处理器
     *
     * @param exception 异常对象
     * @param request 请求对象
     * @param response 响应对象
     * @return RespResult 返回结果
     */
    @ExceptionHandler( {CommonServiceException.class})
    @ResponseBody
    public RespResult exceptionHandler1(Exception exception, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("contentType", "text/html; charset=utf-8");
        if (exception instanceof CommonServiceException) {
            CommonServiceException commonException = (CommonServiceException) exception;
            Throwable cause = exception.getCause();
            boolean isSensitiveException = isSensitiveException1(cause);
            if (isSensitiveException) {
                LOGGER.error("{} Exception: System Exception", OtherUtils.replaceCRLF(request.getRequestURI()));
                printLocalExceptionInfo(cause);
            } else {
                LOGGER.error("{} Exception: ", OtherUtils.replaceCRLF(request.getRequestURI()), exception);
            }
            return RespResult.resultFail(commonException.getErrorCode(), commonException.getErrorMsg());
        } else {
            return RespResult.resultFail(RespCodeEnum.EXP.getCode(), GlobalError.EXCEPTION.getMessage());
        }
    }

    private boolean isSensitiveException1(Throwable cause) {
        /*if (cause instanceof DataAccessException || cause instanceof SQLException
                || cause instanceof ConcurrentModificationException) {
            return true;
        }*/
        if (cause instanceof FileNotFoundException || cause instanceof JarException || isSensitiveException2(cause)) {
            return true;
        }
        return false;
    }

    private boolean isSensitiveException2(Throwable cause) {
        if (cause instanceof MissingResourceException || cause instanceof NotOwnerException
            || cause instanceof BindException) {
            return true;
        }
        if (cause instanceof OutOfMemoryError || cause instanceof StackOverflowError
            || cause instanceof JSONException) {
            return true;
        }
        if (cause instanceof IllegalArgumentException) {
            return true;
        }
        return false;
    }

    private void printLocalExceptionInfo(Throwable exception) {
        StackTraceElement[] stackTrace = exception.getStackTrace();
        for (StackTraceElement stackTraceElement : stackTrace) {
            if (stackTraceElement.getClassName().startsWith("wyh.com")) {
                LOGGER.error(stackTraceElement.toString());
            }
        }
    }
}

ExceptionUtils

public class ExceptionUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionUtils.class);

    /**
     * 脱敏打印异常
     *
     * @param exp 异常对象
     */
    public static void printExceptionInfo(Throwable exp) {
        if (exp instanceof CommonServiceException) {
            if (exp.getCause() == null) {
                printException(exp);
            } else {
                CommonServiceException commonException = (CommonServiceException) exp;
                Throwable cause = exp.getCause();
                boolean isSensitiveException = isSensitiveException1(cause);
                if (isSensitiveException) {
                    LOGGER.error("Exception: {}", commonException.getErrorMsgEn());
                    printLocalExceptionInfo(commonException);
                } else {
                    printException(commonException);
                }
            }
        } else {
            boolean isSensitiveException = isSensitiveException1(exp);
            if (isSensitiveException) {
                LOGGER.error("Exception: System Exception");
                printLocalExceptionInfo(exp);
            } else {
                printException(exp);
            }
        }
    }

    private static boolean isSensitiveException1(Throwable cause) {
        if (cause instanceof FileNotFoundException || cause instanceof JarException || isSensitiveException2(cause)) {
            return true;
        }
        return cause instanceof DataAccessException || cause instanceof SQLException
            || cause instanceof ConcurrentModificationException;
    }

    private static boolean isSensitiveException2(Throwable cause) {
        if (cause instanceof OutOfMemoryError || cause instanceof StackOverflowError
            || cause instanceof JSONException) {
            return true;
        }
        if (cause instanceof IllegalArgumentException) {
            return true;
        }
        return cause instanceof MissingResourceException || cause instanceof NotOwnerException
            || cause instanceof BindException;
    }

    private static void printLocalExceptionInfo(Throwable exception) {
        StackTraceElement[] stackTrace = exception.getStackTrace();
        for (StackTraceElement stackTraceElement : stackTrace) {
            if (stackTraceElement.getClassName().startsWith("wyh.com")) {
                LOGGER.error(stackTraceElement.toString());
            }
        }
    }

    private static void printException(Throwable exp) {
        LOGGER.error("Exception: {}", exp);
    }
}

5.3 测试类,及数据库测试接口

TestController

@Api(tags = { "Swagger2测试Controller" })
@RestController
@RequestMapping("/test")
@Slf4j
public class TestController {

    /* maven中配置的环境常量 */
    @Value("${app.version}")
    String version;
    @Value("${spring.profiles.active}")
    String packagEnvironment;

    /* 配置文件中自定义的常量 */
    @Value("${user.password}")
    String userPassword;

    @Autowired
    private TestService testService;


    @ApiOperation(value = "Hello测试", notes = "无参数测试")
    @GetMapping("/hello")
    public String hello(String name, Map reqParam) {
        return version + " --- " + packagEnvironment + " --- " + userPassword;
    }


    @ApiOperation(value = "Hello测试", notes = "无参数测试")
    @GetMapping("/testMysql")
    public RespResult testMysql(String name, Map reqParam) {
        String testStr = testService.getTestStr();
        return RespResult.resultOK(testStr);
    }
}

service层

public interface TestService {
    String getTestStr();
}


@Service
public class TestServiceImpl implements TestService {

    @Autowired
    private TestDao testDao;

    @Override
    public String getTestStr() {
        return testDao.getTestStr();
    }
}

TestDao

@Mapper
public interface TestDao {

    String getTestStr();
}

TestDao.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="wyh.com.dev.dao.TestDao">

    <select id="getTestStr" resultType="java.lang.String">
        select name from test_user  limit 0,1;
    </select>

</mapper>

5.4 swagger配置

Swagger2Config

@Configuration
@EnableSwagger2
public class Swagger2Config {

    @Bean
    public Docket allDocket() {
        return new Docket(DocumentationType.SWAGGER_2).groupName("所有模块接口")
            .apiInfo(apiInfo())
            .consumes(Collections.singleton(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .produces(Collections.singleton(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .genericModelSubstitutes(ResponseEntity.class)
            .select()
            // 只有标记@ApiOperation才会暴露出给swagger
            .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
            .paths(PathSelectors.regex(".*")) // and by paths
            .build();
    }

    @Bean
    public Docket commonDocket() {
        return new Docket(DocumentationType.SWAGGER_2).groupName("测试组1")
            .apiInfo(apiInfo())
            .consumes(Collections.singleton(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .produces(Collections.singleton(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .genericModelSubstitutes(ResponseEntity.class)
            .select()
            // 只有标记@ApiOperation才会暴露出给swagger
            .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
            .paths(PathSelectors.regex("/test1.*")) // and by paths
            .build();
    }

    @Bean
    public Docket officeDocket() {
        return new Docket(DocumentationType.SWAGGER_2).groupName("测试组2")
            .apiInfo(apiInfo())
            .consumes(Collections.singleton(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .produces(Collections.singleton(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .genericModelSubstitutes(ResponseEntity.class)
            //.genericModelSubstitutes(RespResult2.class)
            .select()
            // 只有标记@ApiOperation才会暴露出给swagger
            .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
            .paths(PathSelectors.regex("/test2.*")) // and by paths
            .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("SpringBoot整合第三方测试API文档")
            .description("RESTful风格接口")
            .termsOfServiceUrl("http://api.wyh.huawei.com")
            .version("1.0.0")
            .build();
    }
}

访问地址:项目访问路径+/swagger-ui.html
例如:http://localhost:16000/Demo_00_1_CreatAndSwagger/swagger-ui.html

5.5 其他工具类

OtherUtils

@Slf4j
public class OtherUtils {

    private static final String COMMAND_WHITE_LIST
            = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890:\\-_./ ";

    public static String replaceCRLF(String message) {
        if (message == null) {
            return "";
        }
        return message.replace('\n', '_').replace('\r', '_');
    }

    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String checkCommand(final String command) {
        if (StringUtils.isBlank(command)) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < command.length(); i++) {
            for (int j = 0; j < COMMAND_WHITE_LIST.length(); j++) {
                if (command.charAt(i) == COMMAND_WHITE_LIST.charAt(j)) {
                    sb.append(COMMAND_WHITE_LIST.charAt(j));
                    break;
                }
            }
        }
        return sb.toString();
    }

    public static boolean checkJson(String jsonStr) {
        try {
            if (StringUtils.isNotEmpty(jsonStr)) {
                JSON.parse(jsonStr);
                return true;
            }
        } catch (Exception exp) {
            log.error("The JSON format is abnormal. jsonStr:{}", jsonStr);
        }
        return false;

    }

    public static void deleteFolderAllFile(String path) {
        File folder = new File(path);
        if (!folder.isDirectory()) {
            return;
        }
        File[] files = folder.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                deleteFolder(file);
            } else {
                if (file.delete()) {
                    log.info("delete file success");
                } else {
                    log.error("delete file failure");
                }
            }
        }
    }

    private static void deleteFolder(File folder) {
        File[] files = folder.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                deleteFolder(file);
            } else {
                if (file.delete()) {
                    log.info("delete file success");
                } else {
                    log.error("delete file failure");
                }
            }
        }
        if (folder.delete()) {
            log.info("delete file success");
        } else {
            log.error("delete file failure");
        }
    }
}

标签:return,springboot,数据源,private,static,Swagger,cause,public,String
From: https://blog.csdn.net/wyh106115/article/details/143158710

相关文章

  • springboot书画在线学习网站-计算机设计毕业源码11849
    springboot书画在线学习网站摘 要本篇论文旨在设计和开发基于SpringBoot的书画在线学习网站,提供用户便捷的学习方式和丰富的学习资源。在该系统中,用户可以通过网站浏览书画的相关内容,包括诗公告消息、书画资讯、课程信息等。同时,系统还将提供书画的学习计划和测试功能,帮......
  • springboot医疗物品采购系统-计算机设计毕业源码10210
    摘 要本文基于SpringBoot框架,设计并实现了一个医疗物品采购系统。该系统旨在解决医疗物品采购中的管理和信息化问题,提供便捷的服务和支持。通过系统的设计与实现,实现了医疗物品的供应商家管理、物品类型管理、物品仓库管理、采购计划管理、采购入库管理、出库申请管理、......
  • 云服务器进阶-部署springboot项目
    一.通过finalshell登录自己的云服务器大家可以下载绑定资源中的finalshell,通过它来访问我们的服务器,二.访问宝塔面板接着我们输入bt进入上文中我们安装过的宝塔面板。输入14查看面板访问地址以及登陆的用户名密码,第一次登陆时会给我们生成一个默认密码,登录之后我们需要......
  • 基于SpringBoot+Vue的鲜牛奶订购管理系统设计与实现毕设(文档+源码)
            目录一、项目介绍二、开发环境三、功能介绍四、核心代码五、效果图六、源码获取:        大家好呀,我是一个混迹在java圈的码农。今天要和大家分享的是一款基于SpringBoot+Vue的鲜牛奶订购管理系统,项目源码请点击文章末尾联系我哦~目前有各类成......
  • JAVA开源项目 基于Vue和SpringBoot在线文档管理系统
    本文项目编号T038,文末自助获取源码\color{red}{T038,文末自助获取源码}......
  • 【开题报告】基于Springboot+vueHPV疫苗预约管理系统(程序+源码+论文) 计算机毕业设计
    本系统(程序+源码)带文档lw万字以上文末可获取一份本项目的java源码和数据库参考。系统程序文件列表开题报告内容研究背景在当今社会,随着健康意识的不断提升,预防疾病已成为人们日益关注的话题。其中,HPV(人乳头瘤病毒)疫苗作为预防宫颈癌等恶性疾病的重要手段,其接种需求在全球......
  • 一篇文章带你了解基于SpringBoot开发的-Ruoyi若依管理系统及其业务程序生成式开发
    一、关于后台管理系统产品    最近看了一下若依管理系统,说它是一套后台管理系统,其实并不是很准确。它应该是一个后台管理系统的基础架子,包括了后台管理系统必备的功能如菜单管理、用户管理、角色管理、字典管理、日志管理、系统监控等,可以免去很多后台管理系统的最初......
  • 基于Springboot麻将棋牌室预约网站设计与实现计算机毕业设计成品和开题报告
      博主介绍:黄菊华老师《Vue.js入门与商城开发实战》《微信小程序商城开发》图书作者,CSDN博客专家,在线教育专家,CSDN钻石讲师;专注大学生毕业设计教育、辅导。所有项目都配有从入门到精通的基础知识视频课程,学习后应对毕业设计答辩,提供核心代码讲解,答辩指导。项目配有对应开......
  • [java毕业设计]免费分享一套SpringBoot+Vue宠物商城网站系统【论文+源码+SQL脚本】,帅
    大家好,我是java1234_小锋老师,看到一个不错的SpringBoot++Vue宠物商城网站系统,分享下哈。项目视频演示【免费】SpringBoot+Vue宠物商城网站系统Java毕业设计_哔哩哔哩_bilibili项目介绍本论文旨在设计与实现一个基于SpringBoot和Vue.js的宠物商城网站系统。随着互联网技......
  • 基于SpringBoot+Vue的药店管理系统设计与实现毕设(文档+源码)
            目录一、项目介绍二、开发环境三、功能介绍四、核心代码五、效果图六、源码获取:        大家好呀,我是一个混迹在java圈的码农。今天要和大家分享的是一款基于SpringBoot+Vue的药店管理系统,项目源码请点击文章末尾联系我哦~目前有各类成品毕......