spring boot 2

服务端验证:

// 1、修改实体
@Min(value = 18,message = "必须大于18岁")
    private int age;

// 2、修改add方法
@PostMapping(value = "/girls")
    public Girl2 Add(@Valid Girl2 g , BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            System.out.println(bindingResult.getFieldError().getDefaultMessage());
            return null;
        }
        return girlRepository.save(g);
    }

AOP

1、添加依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
2、创建类
@Aspect
@Component
public class HttpAspect {
    //拦截Girl2Controller.getList方法 ..表示这个方法任何参数都会被拦截
    @Before("execution(public * com.milan.controller.Girl2Controller.getList(..))")
    public void  log(){
        System.out.println("11111111111");
    }
}
3// Girl2Controller所有的方法都会被拦截
@Before("execution(public * com.milan.controller.Girl2Controller.*(..))")
    @Before("execution(public * com.milan.controller.Girl2Controller.*(..))")
    public void  log(){
        System.out.println("11111111111");
    }
    @After("execution(public * com.milan.controller.Girl2Controller.*(..))")
    public void  afterLog(){
        System.out.println("22222222");
    }
package com.milan.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
@Aspect
@Component
public class HttpAspect {
    private final static Logger logger= (Logger) LoggerFactory.getLogger(HttpAspect.class);
    // 定义一个公用 的方法
    @Pointcut("execution(public * com.milan.controller.Girl2Controller.*(..))")
    public void  log(){
    }
    @Before("log()")
    public void   beforLog(JoinPoint joinPoint){
        ServletRequestAttributes attributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request =attributes.getRequest();
        //url
        logger.info("url={}",request.getRequestURL());
        //method
        logger.info("method={}",request.getMethod());
        //ip
        logger.info("ip={}",request.getRemoteAddr());
        //类方法
        logger.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
        //参数
        logger.info("iargs={}",joinPoint.getArgs());
    }
    @After("log()")
    public void  afterLog(){
        logger.info("2222222222");
    }
    @AfterReturning(returning = "object",pointcut = "log()")
    public  void  afterReturnLog(Object object){
        logger.info("response={}",object);
    }
}

捕获异常,统一处理:

// 1、创建ResultEnt
package com.milan.entity;
public class ResultEnt<T> {
    private Integer code;
    private String msg;
    private T data;
    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
    @Override
    public String toString() {
        return "ResultEnt{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }
}
//2、创建返回码管理枚举
package com.milan.enums;
public enum ResultEnum {
    unknow_error(-1,"未知错误"),
    success(0,"成功"),
    error_小学(100,"你可能还在上小学"),
    error_初中(101,"你可能还在上初中");
    private Integer code;
    private String msg;
    ResultEnum(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }
    public Integer getCode() {
        return code;
    }
    public String getMsg() {
        return msg;
    }
}


//3、创建工具类
package com.milan.utils;
import com.milan.entity.ResultEnt;
import com.milan.enums.ResultEnum;
public class ResultUtil {
    public static ResultEnt success(Object object){
        ResultEnt  resultEnt = new ResultEnt();
        resultEnt.setCode(ResultEnum.success.getCode());
        resultEnt.setMsg(ResultEnum.success.getMsg());
        resultEnt.setData(object);
        return resultEnt;
    }
    public static ResultEnt success(){
        return success(null);
    }
    public static ResultEnt error(Integer code,String message){
        ResultEnt  resultEnt = new ResultEnt();
        resultEnt.setCode(code);
        resultEnt.setMsg(message);
        return resultEnt;
    }
}




//4、创建自定义异常类
package com.milan.handle;
import com.milan.entity.ResultEnt;
import com.milan.entity.exception.MyException;
import com.milan.enums.ResultEnum;
import com.milan.utils.ResultUtil;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class ExceptionHandle {
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultEnt handle(Exception e){
        if( e instanceof MyException){
            MyException myException = (MyException)e;
            return  ResultUtil.error(myException.getCode(),myException.getMessage());
        }
        return ResultUtil.error(ResultEnum.unknow_error.getCode(),ResultEnum.unknow_error.getMsg());
    }
}


//5、使用
package com.milan.service;
import com.milan.entity.Girl2;
import com.milan.entity.exception.MyException;
import com.milan.enums.ResultEnum;
import com.milan.repository.GirlRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
@Service
public class GirlService {
    @Autowired
    private GirlRepository girlRepository;
    @Transactional
    public void insertTwo(){
        Girl2 g = new Girl2();
        g.setName("a");
        g.setAge(1);
        girlRepository.save(g);
        Girl2 a = new Girl2();
        a.setName("ba");
        a.setAge(2);
        girlRepository.save(a);
    }
    public Girl2 getAge(Integer id)throws  Exception{
        Girl2 g = girlRepository.findOne(id);
        Integer age = g.getAge();
        if (age < 10){
            throw new MyException(ResultEnum.error_小学);
        }else if (age >= 10 && age <16 ){
            throw new MyException(ResultEnum.error_初中);
        }
        return g;
    }
}
// ---------Controller使用

    @GetMapping(value = "getage/{id}")
    public ResultEnt  getAge(@PathVariable("id") Integer id) throws Exception{
      return  ResultUtil.success(girlService.getAge(id)) ;
    }

    @PostMapping(value = "/girls")
    public ResultEnt Add(@Valid Girl2 g , BindingResult bindingResult){
        ResultEnt resultEnt = new ResultEnt();

        if (bindingResult.hasErrors()){
           return ResultUtil.error(202,bindingResult.getFieldError().getDefaultMessage());
        }
        return ResultUtil.success(girlRepository.save(g));
    }

//

单元测试

mvn clean package  //打包执行单元测试
mvn clean package -Dmaven.test.skip=true //打包跳过单元测试

右键,goto,test创建单元测试

//测试service
package com.milan.quick;
import com.milan.entity.Girl2;
import com.milan.service.GirlService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class GirlServiceTest {
    @Autowired
    private GirlService girlService;
    @Test
    public void  test01() throws Exception {
        Girl2 girl2 = girlService.getAge(18);
        Assert.assertEquals(17,girl2.getAge());
    }
}

// 测试controller
package com.milan.controller;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class Girl2ControllerTest {
    @Autowired
    private MockMvc mvc;
    @Test
    public void getList() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/g2/girls"))
                .andExpect(MockMvcResultMatchers.status().isOk())
               .andExpect(MockMvcResultMatchers.content().string("abc"));
    }
}

 

posted @ 2018-01-31 10:13  米蓝  阅读(311)  评论(0编辑  收藏  举报