Springboot学习记录二
学习视频:https://www.imooc.com/learn/810
程序代码:git clone http://git.oschina.net/liaoshixiong/girl
1、 使用@Valid表单雁验证
a) 在实体类中添加需要验证的注解
@NotBlank(message = "这个字段必传") private String cupSize; @Min(value = 18, message = "未成年少女禁止入门") // @NotNull // @Max() // @Length() private Integer age; @NotNull(message = "金额必传") private Double money;
b) 在controller中的的参数添加@Valid注解
/** * 添加一个女生 * @return */ @PostMapping(value = "/girls") public Result<Girl> girlAdd(@Valid Girl girl, 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)); }
2、 使用AOP处理请求
a) 添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
b) 建立aspect文件(切入点和逻辑处理)
/** * */ @Aspect @Component public class HttpAspect { private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class); /** * 切入点 */ @Pointcut("execution(public * com.imooc.controller.GirlController.*(..))") public void log() { } @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()); } @After("log()") public void doAfter() { logger.info("222222222222"); } @AfterReturning(returning = "object", pointcut = "log()") public void doAfterReturning(Object object) { logger.info("response={}", object.toString()); } }
c) 000000
3、 统一异常处理
a) 新建异常处理类
/**
* 异常类
*/
public class GirlExceptionextends RuntimeException{
privateInteger code;
public GirlException(ResultEnum resultEnum) {
super(resultEnum.getMsg());
this.code = resultEnum.getCode();
}
publicInteger getCode() {
returncode;
}
publicvoid setCode(Integercode) {
this.code =code;
}
}
b) 程序逻辑总抛出异常
public void getAge(Integer id) throws Exception{
Girl girl = girlRepository.findOne(id);
Integerage = girl.getAge();
if (age< 10){
//返回"你还在上小学吧"code=100
thrownew GirlException(ResultEnum.PRIMARY_SCHOOL);
}else if (age > 10&& age < 16) {
//返回"你可能在上初中"code=101
thrownew GirlException(ResultEnum.MIDDLE_SCHOOL);
}
//如果>16岁,加钱
//...
}
c) 异常枚举类
/**
* 异常结果枚举类
*/
public enum ResultEnum{
UNKONW_ERROR(-1,"未知错误"),
SUCCESS(0,"成功"),
PRIMARY_SCHOOL(100,"我猜你可能还在上小学"),
MIDDLE_SCHOOL(101,"你可能在上初中"),
;
private Integercode;
private Stringmsg;
ResultEnum(Integer code, Stringmsg) {
this.code =code;
this.msg = msg;
}
publicInteger getCode() {
returncode;
}
publicString getMsg() {
returnmsg;
}
}
d) 异常捕获类
/**
* 异常捕获的类
*/
@ControllerAdvice
public class ExceptionHandle{
privatefinal static Logger logger= LoggerFactory.getLogger(ExceptionHandle.class);
@ExceptionHandler(value =Exception.class)
@ResponseBody
publicResult handle(Exception e) {
if(e instanceof GirlException) {
GirlException girlException =(GirlException) e;
return ResultUtil.error(girlException.getCode(),girlException.getMessage());
}else {
logger.error("【系统异常】{}", e);
return ResultUtil.error(-1, "未知错误");
}
}
}
e) 返回结果的工具类
/**
* 结果返回工具类
*/
public class ResultUtil{
publicstatic Result success(Object object) {
Result result = new Result();
result.setCode(0);
result.setMsg("成功");
result.setData(object);
return result;
}
publicstatic Result success() {
returnsuccess(null);
}
publicstatic Result error(Integer code, Stringmsg) {
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
return result;
}
}
f) 返回结果的封装类
/**
* http请求返回的最外层对象
*/
public class Result<T> {
/**错误码. */
privateInteger code;
/**提示信息. */
privateString msg;
/**具体的内容. */
privateT data;
public IntegergetCode() {
returncode;
}
publicvoid setCode(Integercode) {
this.code =code;
}
publicString getMsg() {
returnmsg;
}
publicvoid setMsg(Stringmsg) {
this.msg =msg;
}
publicT getData() {
returndata;
}
publicvoid setData(T data) {
this.data =data;
}
}
4、 单元测试
a) 测试service类
/**
* 测试service类
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class GirlServiceTest{
@Autowired
privateGirlService girlService;
@Test
publicvoid findOneTest(){
Girl girl = girlService.findOne(73);
Assert.assertEquals(new Integer(13), girl.getAge());
}
}
b) 测试controller
/**
* 测试controller
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class GirlControllerTest{
@Autowired
privateMockMvc mvc;
@Test
publicvoid girlList()throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/girls"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string("abc"));
}
}
c) 项目打包自动运行所有测试
i. 使用命令:mvn clean package
d) 打包时自动跳过测试
i. mvnclean package –Dmaven.test.skip=true