springboot 进阶(草稿)

2020-08-02

表单验证:

@PostMapping(value = "/test")
public String add(@Valid people,BindingResult bindingResult){
	if(bindingResult.hasErrors()){
		sout(bindingResult.getFiledError().getDefaultMessage);
		return null;
	}
	//验证通过...
	...

}

实体类:

@Min(value=20, message = "输入的太小了")
private Integer test;

@PathVariable("id") Integer id

AOP:

AOP是一种编程范式,与语言无关,他是一种程序设计思想,它讲通用的逻辑从业务逻辑中分离出来

Spring中使用AOP:
添加依赖:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

拦截器:

aspect包中:

@Aspect
@Component 引入到spring容器中
class test{

	//*也可以是com.wsl.controller.testController.test(..)包名+类名+方法
	@Before("execution(public * com.wsl.controller.*(..))")

	@Pointcut("execution(public * com.wsl.controller.*(..))")
	public void test(){}

	@Before("log()")
	public void testBefore{
	}
}

日志使用:

private final static Logger logger = LoggerFactory.getLogger(testController.class);
logger.info("url={}",test);
logger.error("");

返回内容:

@AfterReturning(returning="object", pointcut="test()")
public void testReturn(Object object){
logger.info("response={}",object.toString);
}

异常处理:

方法采用void,extends exception
之后通过异常捕获

@ControllerAdvice
class test{
	@ExceptionHandler(value=Exception.class)//捕获异常的类

}

枚举:

public enum ResultEnum{
	ERROR(1,"成功"),
	SUCCESS(2,"失败"),
	...;
	private Integer code;
	private String msg;

	ResultEnum(Integer id,String mag){
		this.id = id;
		this.msg = msg;
	}
	get(){
	}
}

测试:

@RunWith(SpringRunner.class)
@SpringBootTest
class test{
	@Test
}

接口测试:

@RunWith(SpringRunner.class)
@SpringBootTest
@AtuoConfigureMockMvc
class test{
	@Autowrited
	private MockMvc mvc;

	@Test
	public void test(){
		mvc.perform(MockMvcRequestBuilders.get("/test"))//API
		.andExpect(MockMvcResultMatchers.status().isOK())//状态码
		.andExpect(MockMvcResultMatchers.content().String("abc"));//返回值
	}
}

mvn打包跳过单元测试:

mvn clean package -Dmaven.test.skip = true;

标题:springboot 进阶(草稿)
作者:sirwsl
地址:https://www.wslhome.top/articles/2020/08/02/1596371777184.html