SpringBoot 精简笔记

0. Fundamental
  a. @SpringBootApplication //启动类
  b. pom.xml //Maven基本依赖

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.4.RELEASE</version>
    <relativePath/>
</parent>

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

1. application.yml (application-dev.yml, application-prod.yml)

    spring:
      profiles:
        active: prod    //设置激活的profile名字

    server:
        port: 8080
        content-path: /demo

    student:
      name: Peter
      age: 19
      message: My name is ${student.name}, age is ${student.age}


    spring: 
        datasource:
            driver-class-name: com.mysql.jdbc.Driver
            url: jdbc:mysql://127.0.0.1:3306/demo
            username: root
            password: 123465
        jpa:
            hibernate:
                dll-auto: update
            show-sql: true

2. 注入设置值
  a. 直接使用单个值:@Value("${student.name}")
  b. 注入配置类:
  @Component
  @ConfigurationProperties(prefix = "student") //一系列配置属性的前缀

3. Controller
  a. @Controller: 处理http请求,返回模板文件名 (旧方式)
  b. @RestController:处理请求,返回json
  @RequestMapping: 配置URL映射
  @GetMapping, @PutMapping, @PostMapping, @DeleteMapping
  @PathVariable //e.g. /hello/{id}
  @RequsetParam //e.g. ?name=Peter

4. Spring-Data-Jpa
  a. @Entity;
  b. @Id (添加annotation @GeneratedValue 来产生自动增长的id值);
  c. Interface class Repository (findOne,findAll,findByXXX,save);
  d. @Service;
  e. @Transactional;

5. Validation
  a. @Min(value=18, message="Less than minimum value."), 最小值,添加到@Entity的property上。
  b. @Valid, BindingResult bindingResult, 绑定验证结果到变量中,如果bindingResult.hasErrors()非空,则获取错误信息:bindingResult.getFieldError()。

6. AOP
  a. 添加依赖 spring-boot-starter-aop;
  b. @Aspect, @Component;
  c. @Pointcut, @Before, @After;
  d. 参数注入:JointPoint,@AfterReturning(returning = "object", pointcut = "log()");

7. 统一异常处理
  a. @ControllerAdvice, @ExceptionHandler;
  b. Self-defined exception, to extend RuntimeException;
  c. Self-defined Enum, to list out all the exception cases;

8. 单元测试
  a. @RunWith(SpringRunner.class), @SpringBootTest(classes = Application.class), @ActiveProfiles("test");

  b. @AutoConfigureMockMvc =>
  @Autowired
  MockMvc mvc;
  mvc.perform(MockMvcRequestBuilders.get("/api")).andExpect(MockMvcResultMatchers.status.isOk());

原文地址:https://www.cnblogs.com/pekkle/p/7191239.html