在pojo类属性的上面添加注解 @Entity public class Girl { @Id @GeneratedValue private Integer id; @NotBlank(message = "这个字段必传") private String cupSize; @Min(value = 18, message = "未成年少女禁止入门") // @NotNull // @Max() // @Length() private Integer age; }
校验使用(使用@valid来验证)java
@PostMapping(value = "/girls") public Result girlAdd(@Valid Girl girl, BindingResult bindingResult) { //使用BindingResult对象输出校验对象的出错信息 if (bindingResult.hasErrors()) { return ResultUtil.error(1, bindingResult.getFieldError().getDefaultMessage()); } girl.setCupSize(girl.getCupSize()); girl.setAge(girl.getAge()); return ResultUtil.success(girlRepository.save(girl)); }
在pom中添加依赖spring
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
并添加AOP操做类编程
@Aspect @Component public class HttpAspect { }
添加方法mvc
@Before("execution(public * com.controller.GirlController.*(..))") public void before() { System.out.println("指定方法以前执行") } @After("execution(public * com.controller.GirlController.*(..))") public void after() { System.out.println("指定方法以后执行") } /** * @Before: 方法执行以前 * @After: 方法执行以后 * @AfterReturning: 方法返回以后 * (..)表示任何参数都会被拦截 * *表明全部 */
若是屡次为这些方法进行切面编程可以使用@Pointcut注解app
@Ponitcut("execution(public * com.controller.GirlController.*(..))") public void log(){} @Before("log()") public void before() { System.out.println("指定方法以前执行") } @After("log()") public void after() { System.out.println("指定方法以后执行") }
实际项目开发中也不推荐使用控制台输出(使用日志输出)ide
@Aspect @Component public class HttpAspect { private final static Looger logger=LoggerFactory.getLogger; @After("log()") public void doAfter() { logger.info("指定方法以后执行") } //输出方法的放回结果 @AfterReturning(returning = "object", pointcut = "log()") public void doAfterReturning(Object object) { logger.info("response={}", object.toString()); } }
@Before("log()") public void doBefore(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("args={}", joinPoint.getArgs()); }
统一异常处理的步骤spring-boot
创建一个Result类 :http请求返回的最外层对象,包括code msg data工具
写一个工具类:优化代码(减小重复代码)单元测试
//===========自定义异常类(spring只能捕获运行时异常,因此继承RuntimeException类)============= public class GirlException extends RuntimeException{ private Integer code; public GirlException(ResultEnum resultEnum) { super(resultEnum.getMsg()); this.code=resultEnum.getCode(); } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } } //==========异常捕获=========== @ControllerAdvice public class ExceptionHandle { private final static Logger logger=LoggerFactory.getLogger(ExceptionHandle.class); @ExceptionHandler(value=Exception.class) @ResponseBody public Result handle(Exception e) { if(e instanceof GirlException) { GirlException girlException=(GirlException)e; return ResultUitl.error(girlException.getCode(), girlException.getMessage()); }else { logger.error("【系统异常】{}",e); return ResultUitl.error(-1, e.getMessage()); } } }
异常出现的状况测试
//=========GirlController======= @RequestMapping("/girlGetAge/{id}") public void getAge(@PathVariable("id") Integer id) throws Exception { girlService.getAge(id); } //==========GirlService============== //异常抛给controller public void getAge(Integer id) throws Exception{ Girl girl=girlRepository.findOne(id); Integer age=girl.getAge(); if(age<10) { throw new GirlException(ResultEnum.PRIMARY_SCHOOL); }else if(age>10 && age<16) { throw new GirlException(ResultEnum.MIDDLE_SCHOOL); } } //=========ResultEnum========== public enum ResultEnum { UNKONW_ERROR(-1,"未知错误"), SUCCESS(0,"成功"), PRIMARY_SCHOOL(100,"你在上小学"), MIDDLE_SCHOOL(101,"你在上初中"), ; private Integer code; private String msg; get\set方法...... }
测试controller @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class GrilController { @Autowired private MockMvc mvc; @Test public void girlList() throws Exception { mvc.perform( MockMvcRequestBuilders.get("/girl/girls")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("abc")); } }