Spring Boot 表单验证、AOP统一处理请求日志、单元测试

一、使用@Valid表单验证

于实体类中添加@Min等注解

 @Entity
public class Girl { @Id
@GeneratedValue
private Integer id; private String cupSize;
@Min(value = 18,message = "未成年禁止入内!")
private Integer age;
...
}

给指定的访问方法参数添加@Valid 注解,并使用BindingResult bindingResult对象获取返回结果

 @PostMapping(value = "/girls")
public Girl addgirl(@Valid Girl girl, BindingResult bindingResult){
if (bindingResult.hasErrors()){
System.out.println(bindingResult.getFieldError().getDefaultMessage());
return null;
}
girl.setCupSize(girl.getCupSize());
girl.setAge(girl.getAge());
return girlRepository.save(girl);
}

Spring Boot 表单验证、AOP统一处理请求日志、单元测试

Spring Boot 表单验证、AOP统一处理请求日志、单元测试

二、使用AOP处理请求

使用AOP统一处理请求日志

在pom文件中添加aop依赖,

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

新建aspect类:

 @Aspect
@Component
public class HttpAspect { @Pointcut("execution(public * com.cenobitor.controller.GirlController.girlList(..))")
public void log(){
} @Before("log()")
public void doBefore(){
System.out.println(11111111);
} @After("log()")
public void doAfter(){
System.out.println(22222222);
} }

 /*
* 以日志的形式取代sout,显示更详细的信息
* */
@Aspect
@Component
public class HttpAspect {
//import org.slf4j.Logger;
private final static Logger LOGGER = LoggerFactory.getLogger(HttpAspect.class);
//设置切点,简化代码
@Pointcut("execution(public * com.cenobitor.controller.GirlController.girlList(..))")
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());
//IP
LOGGER.info("ip={}",request.getRemoteAddr());
//METHOD
LOGGER.info("method={}",request.getMethod());
//类方法
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());
}
}

三、单元测试

  • 基本代码:
 @RestController
public class CustomerController {
@Autowired
private CustomerService customerService; @GetMapping(value = "customer_findById")
public Customer findById(@RequestParam("id") Integer id){
return customerService.findById(id);
}
}vv
 @Service
@Transactional
public class CustomerServiceImpl implements CustomerService {
@Autowired
private CustomerRepository customerRepository; @Override
public Customer findById(Integer id) {
return customerRepository.findOne(id);
}
}
  • service层测试
 @RunWith(SpringRunner.class)
@SpringBootTest
public class CustomerServiceTest {
@Autowired
private CustomerService customerService; @Test
public void findByIdTest(){
Customer customer = customerService.findById(1);
Assert.assertEquals("张三",customer.getName()); }
}
  • API测试(即controller层测试):
 @RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class CustomerControllerTest {
@Autowired
private MockMvc mvc; @Test
public void findById() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/customer_findById?id=1"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string("abc"));//返回结果
}
}
  • 常用命令:
    • 执行打包并进行单元测试

mvn clean package

    • 执行打包并跳过所有单元测试

mvn clean package -Dmaven.test.skip=true

上一篇:清北学堂模拟赛day7 石子合并加强版


下一篇:[转]Python中的with…as…