本文是学习2小时学会Spring Boot和Spring Boot进阶之Web进阶的SpringBoot常用知识点速记。
SpringBoot前置知识:
resources/application.yml
girl:
cupSize: B
age: 18
自动注入类中
@Component
@ConfigurationProperties(prefix = "girl")
public class GirlProperties {
private String cupSize;
private Integer age;
public String getCupSize() {
return cupSize;
}
public void setCupSize(String cupSize) {
this.cupSize = cupSize;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
也可用 @Value("${content}")
resources/application.yml
spring:
profiles:
active: dev
则启动按 application-dev.yml
配置启动, active:prob
则按 application-prob.yml
启动
配置JPA,application.yml
spring:
profiles:
active: dev
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/dbgirl
username: root
password: 123456
jpa:
hibernate:
ddl-auto: create #每次运行应用重新创建表
#ddl-auto: update 有必要才更新
show-sql: true
创建DAO
public interface GirlRepository extends JpaRepository<Girl,Integer> {
public List<Girl> findByAge(Integer age);
}
使用DAO
@Autowired
private GirlRepository girlRepository;
@GetMapping(value = "/girls")
public List<Girl> girlList() {
return girlRepository.findAll();
}
@PostMapping(value = "/girls")
public Girl girlAdd(@RequestParam("cupSize") String cupSize,
@RequestParam("age") Integer age) {
Girl girl = new Girl();
girl.setCupSize(cupSize);
girl.setAge(age);
return girlRepository.save(girl);
}
@GetMapping(value = "/girls/{id}")
public Girl girlFindOne(@PathVariable("id") Integer id) {
return girlRepository.findOne(id);
}
@PutMapping(value = "/girls/{id}")
public Girl girlUpdate(@PathVariable("id") Integer id,
@RequestParam("cupSize") String cupSize,
@RequestParam("age") Integer age) {
Girl girl=new Girl();
girl.setId(id);
girl.setCupSize(cupSize);
girl.setAge(age);
return girlRepository.save(girl);
}//这里注意PUT的请求参数用x-www-form-urlencoded
@DeleteMapping(value = "/girls/{id}")
public String girlDelete(@PathVariable("id") Integer id) {
girlRepository.delete(id);
return "Success!";
}
@GetMapping(value = "/girls/age")
public List<Girl> girlListByAge(@PathVariable("age") Integer age){
return girlRepository.findByAge(age);
}
加一个注解@Transactional
现在 @Entiry
里的成员变量增加 @Min(value=18,message="未成年禁止入内")
,然后在Post请求里, @ValidGirl,BindingResultbindingResult
切的示例
@Aspect
@Component
public class HttpAspect {
private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class.getName());
//切的点
@Pointcut("execution(public * top.linxz.java.controller.GirlController.*(..))")
public void log() {
}
@Before("log()")
public void doBefore(JoinPoint joinPoint) {
//url
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
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("22222222222");
}
@AfterReturning(returning = "object", pointcut = "log()")
public void doAfterReturning(Object object) {
logger.info("response{}", object);
}
}
@ControllerAdvice
public class ExceptionHandle {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handle(Exception e) {
if (e instanceof GirlException) {
GirlException girlException = (GirlException) e;
return ResultUtil.error(girlException.getCode(), girlException.getMessage());
} else {
return ResultUtil.error(-1, "未知错误");
}
}
}
记得Spring里要继承RuntimeException,可以事务回滚。而Exception不会。
public class GirlException extends RuntimeException {
private Integer code;
public GirlException(Integer code, String msg) {
super(msg);
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
普通单元测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class GirlServiceTest {
@Autowired
private GirlService girlService;
@Test
public void findOneTest() {
Girl girl = girlService.findOne(1);
Assert.assertEquals(new Integer(12), girl.getAge());
}
}
Mockc测试HTTP
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class GirlControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void girlList() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/girls"))
.andExpect(MockMvcResultMatchers.status().isOk());
}
}
代码仓库: https://github.com/linxinzhe/java-springboot-girl