spring boot常用代码

spring boot常用代码

spring boot框架结构:

一般先设计数据库

代码编写:

aop层直接抄,config层抄

  1. entity层,实体类层,定义各个字段参数
  2. dao层(mapper层),用于操作数据库,在dao层中一般写操作数据库的方法
  3. dao层的映射文件(.xml文件),位于resources下
  4. service层,服务层,service层下“重写dao层方法(就是直接把方法抄一遍)”,serviceimpl包下是实现service层的方法,重写dao层方法
  5. controller层

aop层

package com.example.demo.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;


@Component
@Aspect
public class LogAopAspect {

    private final static Logger logger = LoggerFactory.getLogger(LogAopAspect.class);

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");

    private long beginTimeMillis;

    @Pointcut("execution(* com.example.demo.controller..*.*(..))")

    public void executeController() {

    }

    @Before("executeController()")
    public void doBeforeAdvice(JoinPoint joinPoint) {
        beginTimeMillis = System.currentTimeMillis();
    }

    @AfterReturning(returning = "keys", pointcut = "executeController()")
    public void doAfterReturningAdvice1(JoinPoint joinPoint, Object keys) throws Exception {
        long intervalTime = System.currentTimeMillis() - beginTimeMillis;
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        SnowFlakeGenerator idWorker = new SnowFlakeGenerator(1, 1);
        String sequenceNo = "EZ" + LocalDateTime.now().format(FORMATTER) + idWorker.nextId();
        InetAddress addr = InetAddress.getLocalHost();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        StringBuilder logInfo = new StringBuilder();
        logInfo.append(" || sequenceno:" + sequenceNo + " || action hostName or ip:" + addr.getHostName().toString() + " or " + addr.getHostAddress().toString());
        logInfo.append("----->> start action  " + " || class_method :" + classMethod + " || requesturl:" + request.getRequestURL().toString());
        logInfo.append(" || requestip :" + request.getRemoteAddr() + " || http_method :" + request.getMethod());
//        logInfo.append(" || requestargs:" + Arrays.toString(joinPoint.getArgs()) + " || response :" + keys);
        logInfo.append(" || step:EndAction1 result:success execution time:" + intervalTime + "ms");
        logger.info(">>>>>>>Controller Request parameter Log:{}" + logInfo.toString());
    }

    @AfterReturning(pointcut = "executeController()", returning = "keys", argNames = "keys")
    public void doAfterReturningAdvice2(String keys) {

    }

    @AfterThrowing(throwing = "exception", pointcut = "executeController()")
    public void doAfterThrowingAdvice(JoinPoint joinPoint, Throwable exception) throws Exception {
        long intervalTime = System.currentTimeMillis() - beginTimeMillis;
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        SnowFlakeGenerator idWorker = new SnowFlakeGenerator(1, 1);
        String sequenceNo = "EZ" + LocalDateTime.now().format(FORMATTER) + idWorker.nextId();
        InetAddress addr = InetAddress.getLocalHost();
        StringBuilder loggerInfo = new StringBuilder();
        loggerInfo.append("sequenceno:" + sequenceNo + " || action hostName or ip:" + addr.getHostName().toString() + " or " + addr.getHostAddress().toString());
        loggerInfo.append("----->> start action" + "  class_method :" + classMethod + " || requesturl:" + request.getRequestURL().toString());
        loggerInfo.append(" || requestip :" + request.getRemoteAddr() + " || http_method :" + request.getMethod());
        loggerInfo.append(" || requestargs:" + Arrays.toString(joinPoint.getArgs()) + " || errorMsg :" + exception.getMessage());
        loggerInfo.append(" || step:EndAction1 result:success execution time:" + intervalTime + "ms");
        if (exception instanceof NullPointerException) { //空指针异常打印
            logger.error(">>>>>>>Controller NullPointerException Log:{}" + loggerInfo.toString(), exception);
        } else {  //业务逻辑异常打印
            logger.error(">>>>>>>Controller Exception Log:{}" + loggerInfo.toString());
        }
    }


    @After("executeController()")
    public void doAfterAdvice(JoinPoint joinPoint) {
    }


    @Around("executeController()")
    public Object doAroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        /*System.out.println("环绕通知的目标方法名:"+proceedingJoinPoint.getSignature().getName());*/
        Object obj = proceedingJoinPoint.proceed();
        return obj;
    }
}

package com.example.demo.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;


@Component
@Aspect
public class LogAopAspect {

    private final static Logger logger = LoggerFactory.getLogger(LogAopAspect.class);

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");

    private long beginTimeMillis;

    @Pointcut("execution(* com.example.demo.controller..*.*(..))")

    public void executeController() {

    }

    @Before("executeController()")
    public void doBeforeAdvice(JoinPoint joinPoint) {
        beginTimeMillis = System.currentTimeMillis();
    }

    @AfterReturning(returning = "keys", pointcut = "executeController()")
    public void doAfterReturningAdvice1(JoinPoint joinPoint, Object keys) throws Exception {
        long intervalTime = System.currentTimeMillis() - beginTimeMillis;
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        SnowFlakeGenerator idWorker = new SnowFlakeGenerator(1, 1);
        String sequenceNo = "EZ" + LocalDateTime.now().format(FORMATTER) + idWorker.nextId();
        InetAddress addr = InetAddress.getLocalHost();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        StringBuilder logInfo = new StringBuilder();
        logInfo.append(" || sequenceno:" + sequenceNo + " || action hostName or ip:" + addr.getHostName().toString() + " or " + addr.getHostAddress().toString());
        logInfo.append("----->> start action  " + " || class_method :" + classMethod + " || requesturl:" + request.getRequestURL().toString());
        logInfo.append(" || requestip :" + request.getRemoteAddr() + " || http_method :" + request.getMethod());
//        logInfo.append(" || requestargs:" + Arrays.toString(joinPoint.getArgs()) + " || response :" + keys);
        logInfo.append(" || step:EndAction1 result:success execution time:" + intervalTime + "ms");
        logger.info(">>>>>>>Controller Request parameter Log:{}" + logInfo.toString());
    }

    @AfterReturning(pointcut = "executeController()", returning = "keys", argNames = "keys")
    public void doAfterReturningAdvice2(String keys) {

    }

    @AfterThrowing(throwing = "exception", pointcut = "executeController()")
    public void doAfterThrowingAdvice(JoinPoint joinPoint, Throwable exception) throws Exception {
        long intervalTime = System.currentTimeMillis() - beginTimeMillis;
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        SnowFlakeGenerator idWorker = new SnowFlakeGenerator(1, 1);
        String sequenceNo = "EZ" + LocalDateTime.now().format(FORMATTER) + idWorker.nextId();
        InetAddress addr = InetAddress.getLocalHost();
        StringBuilder loggerInfo = new StringBuilder();
        loggerInfo.append("sequenceno:" + sequenceNo + " || action hostName or ip:" + addr.getHostName().toString() + " or " + addr.getHostAddress().toString());
        loggerInfo.append("----->> start action" + "  class_method :" + classMethod + " || requesturl:" + request.getRequestURL().toString());
        loggerInfo.append(" || requestip :" + request.getRemoteAddr() + " || http_method :" + request.getMethod());
        loggerInfo.append(" || requestargs:" + Arrays.toString(joinPoint.getArgs()) + " || errorMsg :" + exception.getMessage());
        loggerInfo.append(" || step:EndAction1 result:success execution time:" + intervalTime + "ms");
        if (exception instanceof NullPointerException) { //空指针异常打印
            logger.error(">>>>>>>Controller NullPointerException Log:{}" + loggerInfo.toString(), exception);
        } else {  //业务逻辑异常打印
            logger.error(">>>>>>>Controller Exception Log:{}" + loggerInfo.toString());
        }
    }


    @After("executeController()")
    public void doAfterAdvice(JoinPoint joinPoint) {
    }


    @Around("executeController()")
    public Object doAroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        /*System.out.println("环绕通知的目标方法名:"+proceedingJoinPoint.getSignature().getName());*/
        Object obj = proceedingJoinPoint.proceed();
        return obj;
    }
}

package com.sunywonders.xiaoshangzhushouwx.aop;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * RestTemplate的配置类
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(1000 * 60);                                           //读取超时时间为单位为60秒
        factory.setConnectTimeout(1000 * 10);                                        //连接超时时间设置为10秒
        return factory;
    }
}

config文件

swagger配置文件

package com.sunywonders.xiaoshangzhushou.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

//参考:http://blog.csdn.net/catoop/article/details/50668896

/**
 * @author yanhiatao
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {

    @Bean
    public Docket createRestApi() {
        List<Parameter> pars = new ArrayList<Parameter>();
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(pars)
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("待定 RESTful API")
                .description("名称")
                .termsOfServiceUrl("https://www.cnblogs.com/xiebq/")
                .version("1")
                .build();
    }

}

.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="">


</mapper>

配置异常处理

配置全局异常:

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(CustomException.class)
    public Result handleException(CustomException e) {
        // 打印异常信息
        log.error("### 异常信息:{} ###", e.getMessage());
        return new Result(e.getResultCode());
    }

    /**
     * 参数错误异常
     */
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    public Result handleException(Exception e) {

        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException validException = (MethodArgumentNotValidException) e;
            BindingResult result = validException.getBindingResult();
            StringBuffer errorMsg = new StringBuffer();
            if (result.hasErrors()) {
                List<ObjectError> errors = result.getAllErrors();
                errors.forEach(p -> {
                    FieldError fieldError = (FieldError) p;
                    errorMsg.append(fieldError.getDefaultMessage()).append(",");
                    log.error("### 请求参数错误:{" + fieldError.getObjectName() + "},field{" + fieldError.getField() + "},errorMessage{" + fieldError.getDefaultMessage() + "}");
                });
            }
        } else if (e instanceof BindException) {
            BindException bindException = (BindException) e;
            if (bindException.hasErrors()) {
                log.error("### 请求参数错误: {}", bindException.getAllErrors());
            }
        }

        return new Result(ResultCode.PARAM_IS_INVALID);
    }

    /**
     * 处理所有不可知的异常
     */
    @ExceptionHandler(Exception.class)
    public Result handleOtherException(Exception e) {
        //打印异常堆栈信息
        e.printStackTrace();
        // 打印异常信息
        log.error("### 不可知的异常:{} ###", e.getMessage());
        return new Result(ResultCode.SYSTEM_INNER_ERROR);
    }

}

自定义异常:

定义异常继承异常后,自动生成5个文件

public class DemoException extends RuntimeException{
    private static final long serialVersionUID = -4978764707149183316L;   //可自动生成
    
    //自动生成5个文件
    //Alt+Insert
}
原文地址:https://www.cnblogs.com/fkxiaozhou/p/13889011.html