数据校验、异常处理、单元测试、打包、日志
[toc]
数据校验
在 model 增加注解 @Min(value = 18,message = "不能小于18岁")
@Entity
public class Person {
@Id
@GeneratedValue
private Integer id;
private String name;
@Min(value = 18,message = "不能小于18岁")
private Integer age;
。。。set、get 方法
}
在 controller 的 model 增加@Valid
注解,同时可以BindingResult
获取校验的信息。
@PostMapping(value = "/addPerson")
public Person addPerson(@Valid Person person, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
//输出错误信息:不能小于18岁
System.out.print(bindingResult.getFieldError().getDefaultMessage());
}
return personRespository.save(person);
}
异常处理
定义常量枚举:ResultEnum.java
public enum ResultEnum {
UNKNOW(-1, "未知错误"),
OKKK(100, "小于18岁"),
NOOO(101, "大于50岁"),;
private Integer code;
private String msg;
ResultEnum(Integer code, String mag) {
this.code = code;
this.msg = mag;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMag() {
return msg;
}
public void setMag(String mag) {
this.msg = mag;
}
}
自定义异常类:PersonException.java
public class PersonException extends Exception {
private Integer code;
private String msg;
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 PersonException(ResultEnum resultEnum) {
this.code = resultEnum.getCode();
this.msg = resultEnum.getMag();
}
}
定义返回结果类:ResultInfo.java
public class ResultInfo<T> implements Serializable {
private int code;
private String msg;
private T data;
public ResultInfo(int code, String msg) {
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int 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;
}
}
全局异常处理类:ResultExceptionHandle.java
@ControllerAdvice
public class ResultExceptionHandle {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ResultInfo handleException(HttpServletRequest request, Exception e) {
if (e instanceof PersonException) {
PersonException personException = (PersonException) e;
return new ResultInfo(personException.getCode(), personException.getMsg());
}
return new ResultInfo(-1, "未知错误");
}
}
Controller 正常调用,全局 Exception 会自动拦截处理 HelloController.java
@RestController
public class HelloController {
@Autowired
private PersonRespository personRespository;
@PostMapping(value = "/addPerson")
public Person addPerson(@Valid Person person, BindingResult bindingResult) throws Exception {
if (bindingResult.hasErrors()) {
//输出错误信息
System.out.print(bindingResult.getFieldError().getDefaultMessage());
}
return personService.save(person);
}
}
单元测试
需要模拟 http 请求进行单元测试,类上要添加注解(@RunWith(SpringRunner.class)
、@SpringBootTest
、@AutoConfigureMockMvc
),方法上也要添加注解(@Test
),使用MockMvc进行请求模拟。
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class PersonControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void findPerson() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/findPersons")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().string("hello"));
}
}
打包默认会运行所有单元测试,可以通过参数跳过单元测试。
打包
如果需要打包发布应用的话,可以打包成 jar(docker用这种方式) 或者 war(老方式)
还需要在增加一个打包插件:spring-boot-maven-plugin
pom.xml
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
使用命令:
mvn package
默认在 target
目录下生成 jar
或者 war
文件,jar
可以直接使用 jdk 运行,war
需要放到 tomcat
的 webapp
目录下。
java -jar spring-boot-demo-1.0-SNAPSHOT.jar
日志
public static Logger logger = LoggerFactory.getLogger(HttpAspect.class);
@Pointcut("execution(public * com.example.HelloController.*(..))")
public void log() {
}
@Before("log()")
public void logBefore() {
logger.info("logBefore");
}
@After("log()")
public void logAfter() {
logger.info("logAfter");
}
网友评论