github主页示例:https://github.com/tianyunperfect/springboot-parent.git
初始化web
pom
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
<layout>ZIP</layout>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
</dependencies>
<!--锁定springCloud版本-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
application.yml
新建配置文件 application.yml,可以有多个配置文件,线上可以在jar包同级目录新建config/application.yml,启动时会优先读取。
**
#可以配置启动文件
spring:
profiles:
active: dev
#可以修改端口号和启动路径
server:
port: 8080
servlet:
context-path: /girl
其他配置文件:
application-dev.yml:开发环境
application-test.yml:测试环境
application-prod.yml:生产环境
启动脚本:
java -jar target/girl-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod
启动文件
application.java
@SpringBootApplication
public class LogApplication {
public static void main(String[] args) {
SpringApplication.run(LogApplication.class, args);
}
}
打印日志
1、开启AOP
<!--开启aop-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2、添加日志切片:aspect/LogAspect.java
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* 日志切片
*
* @author tianyunperfect
* Created on 2019/9/19
*/
@Component
@Aspect
@Slf4j
public class LogAspect {
@Pointcut("execution(public * com.alvin.controller..*.*(..))")
public void webLog() {
}
@Around("webLog()")
public Object doBefore(ProceedingJoinPoint joinPoint) throws Throwable {
/**
* 执行方法之前
*/
long start = System.currentTimeMillis();
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
/**
* 执行方法
*/
Object result = joinPoint.proceed();
/**
* 执行方法之后
*/
StringBuilder sb = new StringBuilder();
String split = "; ";
sb.append("url=" + request.getRequestURL() + split);
sb.append("method=" + request.getMethod() + split);
sb.append("class_method=" + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() + split);
sb.append("args=" + new Gson().toJson(joinPoint.getArgs()) + split);
sb.append("consumer time(ms) = " + (System.currentTimeMillis() - start));
log.info(sb.toString());
return result;
}
}
3、设置日志打印格式和位置,如果不设置会使用默认。
语雀内容
设置基础entity
1、状态值
ResultCode.java
public enum ResultCode {
// 基本
SUCCESS(1, "success"),
FAIL(-1, "fail"),
UNKNOW(-2, "unknow"),
;
private Integer code;
private String message;
ResultCode(Integer code, String message) {
this.code = code;
this.message = message;
}
}
2、controller返回的result
Result.java
package com.alvin.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.ArrayList;
/**
* @Description
* @Author 田云
* @Date 2020/5/1 20:54
* @Version 1.0
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> implements Serializable {
private boolean success;
private Integer code;
private String message;
private T data;
public static <T> Result result(Boolean flag, ResultCode resultCode, T data) {
return new Result(flag, resultCode.ordinal(), resultCode.name(), data);
}
public static <T> Result success(ResultCode resultCode, T data) {
return result(true, resultCode, data);
}
public static <T> Result success(T data) {
return success(ResultCode.SUCCESS, data);
}
public static Result success() {
return success(null);
}
public static <T> Result failure(Integer code, String message) {
return new Result(false, code, message, null);
}
public static <T> Result failure(ResultCode resultCode) {
return new Result(false, resultCode.ordinal(), resultCode.name(), null);
}
public static <T> Result failure() {
return failure(ResultCode.FAIL);
}
public static void main(String[] args) {
ArrayList<String> strings = new ArrayList<>();
strings.add("12");
System.out.println(Result.success(strings));
}
}
3、分页实体类
PageResult.java
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.List;
/**
* @Description
* @Author 田云
* @Date 2020/5/1 21:12
* @Version 1.0
*/
@Data
@AllArgsConstructor
public class PageResult<T> {
/**
* 第几页
*
* @mock 1
*/
private Integer currentPage;
/**
* 每页数量
*
* @mock 10
*/
private Integer pageSize;
/**
* 总数
*
* @mock @integer(9,99)
*/
private Long total;
private List<T> list;
}
捕获controller异常
通过全局异常来处理,这里我们直接捕获所有controller异常,也可以单独放在某一个controller里面。
handle/ExceptionHandle.java
import com.unisound.common.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Class ExceptionHandle ...
*s
* @author tianyunperfect
* Created on 2019/9/19
*/
@ControllerAdvice
@Slf4j
public class ExceptionHandle {
/**
* 统一异常处理
* @param e
* @return
*/
@ResponseBody
@ExceptionHandler
public Result exceptionHandle(Exception e) {
e.printStackTrace();
log.error("系统异常:{}", e.getMessage());
return Result.error(ResultCode.UNKNOW.ordinal(), e.getMessage());
}
}
前端接收Long精度问题
我们把long类型数据传到前端时,会丢失精度,这里加一个配置类即可(将long转换为string)
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.util.List;
@Configuration
public class LongToStringJsonConfig extends WebMvcConfigurationSupport {
/**
* 这个必须有,否则不能访问静态文件
* @param configurer
*/
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
/**
* 配置Long转string
* @param converters
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
jackson2HttpMessageConverter.setObjectMapper(objectMapper);
converters.add(jackson2HttpMessageConverter);
}
}