github主页示例:https://github.com/tianyunperfect/springboot-parent.git

初始化web

pom

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.1.5.RELEASE</version>
  5. <relativePath/>
  6. </parent>
  7. <properties>
  8. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  9. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  10. <java.version>1.8</java.version>
  11. </properties>
  12. <build>
  13. <plugins>
  14. <plugin>
  15. <groupId>org.springframework.boot</groupId>
  16. <artifactId>spring-boot-maven-plugin</artifactId>
  17. <configuration>
  18. <fork>true</fork>
  19. <layout>ZIP</layout>
  20. </configuration>
  21. </plugin>
  22. </plugins>
  23. </build>
  24. <dependencies>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter-web</artifactId>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-starter-test</artifactId>
  32. <scope>test</scope>
  33. </dependency>
  34. <dependency>
  35. <groupId>org.springframework.boot</groupId>
  36. <artifactId>spring-boot-devtools</artifactId>
  37. <scope>runtime</scope>
  38. <optional>true</optional>
  39. </dependency>
  40. <!-- lombok -->
  41. <dependency>
  42. <groupId>org.projectlombok</groupId>
  43. <artifactId>lombok</artifactId>
  44. <version>1.18.4</version>
  45. </dependency>
  46. <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
  47. <dependency>
  48. <groupId>com.alibaba</groupId>
  49. <artifactId>fastjson</artifactId>
  50. <version>1.2.56</version>
  51. </dependency>
  52. <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
  53. <dependency>
  54. <groupId>com.google.code.gson</groupId>
  55. <artifactId>gson</artifactId>
  56. <version>2.8.5</version>
  57. </dependency>
  58. </dependencies>
  59. <!--锁定springCloud版本-->
  60. <dependencyManagement>
  61. <dependencies>
  62. <dependency>
  63. <groupId>org.springframework.cloud</groupId>
  64. <artifactId>spring-cloud-dependencies</artifactId>
  65. <version>Greenwich.SR2</version>
  66. <type>pom</type>
  67. <scope>import</scope>
  68. </dependency>
  69. </dependencies>
  70. </dependencyManagement>

application.yml


新建配置文件 application.yml,可以有多个配置文件,线上可以在jar包同级目录新建config/application.yml,启动时会优先读取。

**

  1. #可以配置启动文件
  2. spring:
  3. profiles:
  4. active: dev
  5. #可以修改端口号和启动路径
  6. server:
  7. port: 8080
  8. servlet:
  9. context-path: /girl

其他配置文件:
application-dev.yml:开发环境
application-test.yml:测试环境
application-prod.yml:生产环境

启动脚本:

  1. java -jar target/girl-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod

启动文件

application.java

  1. @SpringBootApplication
  2. public class LogApplication {
  3. public static void main(String[] args) {
  4. SpringApplication.run(LogApplication.class, args);
  5. }
  6. }

打印日志


1、开启AOP

  1. <!--开启aop-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-aop</artifactId>
  5. </dependency>

2、添加日志切片:aspect/LogAspect.java

  1. import com.google.gson.Gson;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.aspectj.lang.ProceedingJoinPoint;
  4. import org.aspectj.lang.annotation.Around;
  5. import org.aspectj.lang.annotation.Aspect;
  6. import org.aspectj.lang.annotation.Pointcut;
  7. import org.springframework.stereotype.Component;
  8. import org.springframework.web.context.request.RequestContextHolder;
  9. import org.springframework.web.context.request.ServletRequestAttributes;
  10. import javax.servlet.http.HttpServletRequest;
  11. /**
  12. * 日志切片
  13. *
  14. * @author tianyunperfect
  15. * Created on 2019/9/19
  16. */
  17. @Component
  18. @Aspect
  19. @Slf4j
  20. public class LogAspect {
  21. @Pointcut("execution(public * com.alvin.controller..*.*(..))")
  22. public void webLog() {
  23. }
  24. @Around("webLog()")
  25. public Object doBefore(ProceedingJoinPoint joinPoint) throws Throwable {
  26. /**
  27. * 执行方法之前
  28. */
  29. long start = System.currentTimeMillis();
  30. HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
  31. /**
  32. * 执行方法
  33. */
  34. Object result = joinPoint.proceed();
  35. /**
  36. * 执行方法之后
  37. */
  38. StringBuilder sb = new StringBuilder();
  39. String split = "; ";
  40. sb.append("url=" + request.getRequestURL() + split);
  41. sb.append("method=" + request.getMethod() + split);
  42. sb.append("class_method=" + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() + split);
  43. sb.append("args=" + new Gson().toJson(joinPoint.getArgs()) + split);
  44. sb.append("consumer time(ms) = " + (System.currentTimeMillis() - start));
  45. log.info(sb.toString());
  46. return result;
  47. }
  48. }

3、设置日志打印格式和位置,如果不设置会使用默认。

语雀内容

设置基础entity

1、状态值

ResultCode.java

  1. public enum ResultCode {
  2. // 基本
  3. SUCCESS(1, "success"),
  4. FAIL(-1, "fail"),
  5. UNKNOW(-2, "unknow"),
  6. ;
  7. private Integer code;
  8. private String message;
  9. ResultCode(Integer code, String message) {
  10. this.code = code;
  11. this.message = message;
  12. }
  13. }

2、controller返回的result

Result.java

  1. package com.alvin.model;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.NoArgsConstructor;
  5. import java.io.Serializable;
  6. import java.util.ArrayList;
  7. /**
  8. * @Description
  9. * @Author 田云
  10. * @Date 2020/5/1 20:54
  11. * @Version 1.0
  12. */
  13. @Data
  14. @NoArgsConstructor
  15. @AllArgsConstructor
  16. public class Result<T> implements Serializable {
  17. private boolean success;
  18. private Integer code;
  19. private String message;
  20. private T data;
  21. public static <T> Result result(Boolean flag, ResultCode resultCode, T data) {
  22. return new Result(flag, resultCode.ordinal(), resultCode.name(), data);
  23. }
  24. public static <T> Result success(ResultCode resultCode, T data) {
  25. return result(true, resultCode, data);
  26. }
  27. public static <T> Result success(T data) {
  28. return success(ResultCode.SUCCESS, data);
  29. }
  30. public static Result success() {
  31. return success(null);
  32. }
  33. public static <T> Result failure(Integer code, String message) {
  34. return new Result(false, code, message, null);
  35. }
  36. public static <T> Result failure(ResultCode resultCode) {
  37. return new Result(false, resultCode.ordinal(), resultCode.name(), null);
  38. }
  39. public static <T> Result failure() {
  40. return failure(ResultCode.FAIL);
  41. }
  42. public static void main(String[] args) {
  43. ArrayList<String> strings = new ArrayList<>();
  44. strings.add("12");
  45. System.out.println(Result.success(strings));
  46. }
  47. }

3、分页实体类

PageResult.java

  1. import lombok.AllArgsConstructor;
  2. import lombok.Data;
  3. import java.util.List;
  4. /**
  5. * @Description
  6. * @Author 田云
  7. * @Date 2020/5/1 21:12
  8. * @Version 1.0
  9. */
  10. @Data
  11. @AllArgsConstructor
  12. public class PageResult<T> {
  13. /**
  14. * 第几页
  15. *
  16. * @mock 1
  17. */
  18. private Integer currentPage;
  19. /**
  20. * 每页数量
  21. *
  22. * @mock 10
  23. */
  24. private Integer pageSize;
  25. /**
  26. * 总数
  27. *
  28. * @mock @integer(9,99)
  29. */
  30. private Long total;
  31. private List<T> list;
  32. }

捕获controller异常

通过全局异常来处理,这里我们直接捕获所有controller异常,也可以单独放在某一个controller里面。

handle/ExceptionHandle.java

  1. import com.unisound.common.entity.Result;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.web.bind.annotation.ControllerAdvice;
  4. import org.springframework.web.bind.annotation.ExceptionHandler;
  5. import org.springframework.web.bind.annotation.ResponseBody;
  6. /**
  7. * Class ExceptionHandle ...
  8. *s
  9. * @author tianyunperfect
  10. * Created on 2019/9/19
  11. */
  12. @ControllerAdvice
  13. @Slf4j
  14. public class ExceptionHandle {
  15. /**
  16. * 统一异常处理
  17. * @param e
  18. * @return
  19. */
  20. @ResponseBody
  21. @ExceptionHandler
  22. public Result exceptionHandle(Exception e) {
  23. e.printStackTrace();
  24. log.error("系统异常:{}", e.getMessage());
  25. return Result.error(ResultCode.UNKNOW.ordinal(), e.getMessage());
  26. }
  27. }

前端接收Long精度问题

我们把long类型数据传到前端时,会丢失精度,这里加一个配置类即可(将long转换为string)

  1. import com.fasterxml.jackson.databind.ObjectMapper;
  2. import com.fasterxml.jackson.databind.module.SimpleModule;
  3. import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.http.converter.HttpMessageConverter;
  6. import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
  7. import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
  8. import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
  9. import java.util.List;
  10. @Configuration
  11. public class LongToStringJsonConfig extends WebMvcConfigurationSupport {
  12. /**
  13. * 这个必须有,否则不能访问静态文件
  14. * @param configurer
  15. */
  16. @Override
  17. public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
  18. configurer.enable();
  19. }
  20. /**
  21. * 配置Long转string
  22. * @param converters
  23. */
  24. @Override
  25. public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
  26. MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
  27. ObjectMapper objectMapper = new ObjectMapper();
  28. SimpleModule simpleModule = new SimpleModule();
  29. simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
  30. simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
  31. objectMapper.registerModule(simpleModule);
  32. jackson2HttpMessageConverter.setObjectMapper(objectMapper);
  33. converters.add(jackson2HttpMessageConverter);
  34. }
  35. }