1. @SpringBootApplication

  1. @SpringBootApplication
  2. public class BootApplication {
  3. public static void main(String[] args) {
  4. SpringApplication.run(BootApplication.class, args);
  5. }
  6. }

我们可以把 @SpringBootApplication看作是 @Configuration、@EnableAutoConfiguration、@ComponentScan 注解的集合。

  1. package org.springframework.boot.autoconfigure;
  2. @Target(ElementType.TYPE)
  3. @Retention(RetentionPolicy.RUNTIME)
  4. @Documented
  5. @Inherited
  6. @SpringBootConfiguration
  7. @EnableAutoConfiguration
  8. @ComponentScan(excludeFilters = {
  9. @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
  10. @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
  11. public @interface SpringBootApplication {
  12. ......
  13. }
  14. package org.springframework.boot;
  15. @Target(ElementType.TYPE)
  16. @Retention(RetentionPolicy.RUNTIME)
  17. @Documented
  18. @Configuration
  19. public @interface SpringBootConfiguration {
  20. }

根据 SpringBoot 官网,这三个注解的作用分别是:

  • @EnableAutoConfiguration:启用 SpringBoot 的自动配置机制
  • @ComponentScan: 扫描被@Component (@Service,@Controller)注解的 bean,注解默认会扫描该类所在的包下所有的类。
  • @Configuration:允许在 Spring 上下文中注册额外的 bean 或导入其他配置类

    2. Spring Bean相关

    2.1 @Autowaired

    自动导入对象到类中,被注入进的类同样要被 Spring 容器管理比如:Service 类注入到 Controller 类中。 ```java @Service public class UserService { …… }

@RestController @RequestMapping(“/users”) public class UserController { @Autowired private UserService userService; …… }

  1. <a name="LNLML"></a>
  2. ## 2.2 `@Component`,`@Repository`,`@Service`,`@Controller`
  3. 我们一般使用 @Autowired 注解让 Spring 容器帮我们自动装配 bean。要想把类标识成可用于 @Autowired 注解自动装配的 bean 的类,可以采用以下注解实现:
  4. - @Component :通用的注解,可标注任意类为 Spring 组件。如果一个 Bean 不知道属于哪个层,可以使用@Component 注解标注。
  5. - @Repository : 对应持久层即 Dao 层,主要用于数据库相关操作。
  6. - @Service : 对应服务层,主要涉及一些复杂的逻辑,需要用到 Dao 层。
  7. - @Controller : 对应 Spring MVC 控制层,主要用于接受用户请求并调用 Service 层返回数据给前端页面。
  8. <a name="F8ld8"></a>
  9. ## 2.3 `@RestController`
  10. @RestController注解是@Controller和@ResponseBody的合集,表示这是个控制器 bean,并且是将函数的返回值直 接填入 HTTP 响应体中,是 REST 风格的控制器。<br />单独使用 @Controller 不加 @ResponseBody的话一般使用在要返回一个视图的情况,这种情况属于比较传统的 Spring MVC 的应用,对应于前后端不分离的情况。@Controller +@ResponseBody 返回 JSON 或 XML 形式数据<br />关于@RestController 和 @Controller的对比,请看这篇文章:[@RestController vs @Controller](https://mp.weixin.qq.com/s?__biz=Mzg2OTA0Njk0OA==&mid=2247485544&idx=1&sn=3cc95b88979e28fe3bfe539eb421c6d8&chksm=cea247a3f9d5ceb5e324ff4b8697adc3e828ecf71a3468445e70221cce768d1e722085359907&token=1725092312&lang=zh_CN#rd)。
  11. <a name="Bd33H"></a>
  12. ## 2.4 `@Scope`
  13. 声明 Spring Bean 的作用域,使用方法:
  14. ```java
  15. @Bean
  16. @Scope("singleton")
  17. public Person personSingleton() {
  18. return new Person();
  19. }

四种常见的 Spring Bean 的作用域:

  • singleton : 唯一 bean 实例,Spring 中的 bean 默认都是单例的。
  • prototype : 每次请求都会创建一个新的 bean 实例。
  • request : 每一次 HTTP 请求都会产生一个新的 bean,该 bean 仅在当前 HTTP request 内有效。
  • session : 每一次 HTTP 请求都会产生一个新的 bean,该 bean 仅在当前 HTTP session 内有效。

    2.5 @Configuration

    一般用来声明配置类,可以使用 @Component注解替代,不过使用@Configuration注解声明配置类更加语义化。 ```java @Configuration public class AppConfig { @Bean public TransferService transferService() {
    1. return new TransferServiceImpl();
    }

}

  1. <a name="Uyh8F"></a>
  2. # 3. 处理常见的HTTP请求类型
  3. **5 种常见的请求类型:**
  4. - **GET** :请求从服务器获取特定资源。举个例子:GET /users(获取所有学生)
  5. - **POST** :在服务器上创建一个新的资源。举个例子:POST /users(创建学生)
  6. - **PUT** :更新服务器上的资源(客户端提供更新后的整个资源)。举个例子:PUT /users/12(更新编号为 12 的学生)
  7. - **DELETE** :从服务器删除特定的资源。举个例子:DELETE /users/12(删除编号为 12 的学生)
  8. - **PATCH** :更新服务器上的资源(客户端提供更改的属性,可以看做作是部分更新),使用的比较少,这里就不举例子了。
  9. <a name="A0U2V"></a>
  10. ## 3.1 GET请求
  11. @GetMapping("users") 等价于@RequestMapping(value="/users",method=RequestMethod.GET)
  12. ```java
  13. @GetMapping("/users")
  14. public ResponseEntity<List<User>> getAllUsers() {
  15. return userRepository.findAll();
  16. }

3.2 POST请求

@PostMapping(“users”) 等价于@RequestMapping(value=”/users”,method=RequestMethod.POST)

  1. @PostMapping("/users")
  2. public ResponseEntity<User> createUser(@Valid @RequestBody UserCreateRequest userCreateRequest) {
  3. return userRespository.save(user);
  4. }

3.3 PUT请求

@PutMapping(“/users/{userId}”) 等价@RequestMapping(value=”/users/{userId}”,method=RequestMethod.PUT)

  1. @PutMapping("/users/{userId}")
  2. public ResponseEntity<User> updateUser(@PathVariable(value = "userId") Long userId,
  3. @Valid @RequestBody UserUpdateRequest userUpdateRequest) {
  4. ......
  5. }

3.4 DELETE请求

@DeleteMapping(“/users/{userId}”)等价:@RequestMapping(value=”/users/{userId}”,method=RequestMethod.DELETE)

  1. @DeleteMapping("/users/{userId}")
  2. public ResponseEntity deleteUser(@PathVariable(value = "userId") Long userId){
  3. ......
  4. }

3.5 PATCH请求

一般实际项目中,我们都是 PUT 不够用了之后才用 PATCH 请求去更新数据。

  1. @PatchMapping("/profile")
  2. public ResponseEntity updateStudent(@RequestBody StudentUpdateRequest studentUpdateRequest) {
  3. studentRepository.updateDetail(studentUpdateRequest);
  4. return ResponseEntity.ok().build();
  5. }

4. 前后端传值

4.1 @PathVariable@RequestParm

@PathVariable用于获取路径参数,@RequestParam用于获取查询参数。
举个简单的例子:

  1. @GetMapping("/klasses/{klassId}/teachers")
  2. public List<Teacher> getKlassRelatedTeachers(
  3. @PathVariable("klassId") Long klassId,
  4. @RequestParam(value = "type", required = false) String type ) {
  5. ...
  6. }

如果我们请求的 url 是:/klasses/{123456}/teachers?type=web,那么我们服务获取到的数据就是:klassId=123456,type=web。

4.2 @RequestBody

用于读取 Request 请求(可能是 POST,PUT,DELETE,GET 请求)的 body 部分并且Content-Type 为 application/json 格式的数据,接收到数据之后会自动将数据绑定到 Java 对象上去。系统会使用HttpMessageConverter或者自定义的HttpMessageConverter将请求的 body 中的 json 字符串转换为 java 对象。
简单的例子来给演示一下基本使用:
我们有一个注册的接口:

  1. @PostMapping("/sign-up")
  2. public ResponseEntity signUp(@RequestBody @Valid UserRegisterRequest userRegisterRequest) {
  3. userService.save(userRegisterRequest);
  4. return ResponseEntity.ok().build();
  5. }

UserRegisterRequest对象:

  1. @Data
  2. @AllArgsConstructor
  3. @NoArgsConstructor
  4. public class UserRegisterRequest {
  5. @NotBlank
  6. private String userName;
  7. @NotBlank
  8. private String password;
  9. @NotBlank
  10. private String fullName;
  11. }

我们发送 post 请求到这个接口,并且 body 携带 JSON 数据:

  1. {"userName":"coder","fullName":"shuangkou","password":"123456"}

这样我们的后端就可以直接把 json 格式的数据映射到我们的 UserRegisterRequest 类上。
Spring/SpringBoot常见注解总结 - 图1
需要注意的是:一个请求方法只可以有一个@RequestBody,但是可以有多个@RequestParam和@PathVariable。 如果你的方法必须要用两个 @RequestBody来接受数据的话,大概率是你的数据库设计或者系统设计出问题了!

5. 读取配置信息

很多时候我们需要将一些常用的配置信息比如阿里云 oss、发送短信、微信认证的相关配置信息等等放到配置文件中。
下面我们来看一下Spring为我们提供了哪些方式帮助我们从配置文件中读取这些配置信息。
我们的数据源application.yml内容如下:

  1. wuhan2020: 2020年初武汉爆发了新型冠状病毒,疫情严重,但是,我相信一切都会过去!武汉加油!中国加油!
  2. my-profile:
  3. name: xkd
  4. email: xukedong96@163.com
  5. library:
  6. location: 湖北武汉加油中国加油
  7. books:
  8. - name: 天才基本法
  9. description: 二十二岁的林朝夕在父亲确诊阿尔茨海默病这天,得知自己暗恋多年的校园男神裴之即将出国深造的消息——对方考取的学校,恰是父亲当年为她放弃的那所。
  10. - name: 时间的秩序
  11. description: 为什么我们记得过去,而非未来?时间“流逝”意味着什么?是我们存在于时间之内,还是时间存在于我们之中?卡洛·罗韦利用诗意的文字,邀请我们思考这一亘古难题——时间的本质。
  12. - name: 了不起的我
  13. description: 如何养成一个新习惯?如何让心智变得更成熟?如何拥有高质量的关系? 如何走出人生的艰难时刻?

5.1 @value常用

使用 @Value(“${property}”) 读取比较简单的配置信息:

  1. @Value("${wuhan2020}")
  2. String wuhan2020;

5.2 @ConfigurationProperties(常用)

通过@ConfigurationProperties读取配置信息并与 bean 绑定。

  1. @Component
  2. @ConfigurationProperties(prefix = "library")
  3. class LibraryProperties {
  4. @NotEmpty
  5. private String location;
  6. private List<Book> books;
  7. @Setter
  8. @Getter
  9. @ToString
  10. static class Book {
  11. String name;
  12. String description;
  13. }
  14. 省略getter/setter
  15. ......
  16. }

5.3 PropertySource(不常用)

@PropertySource读取指定 properties 文件

  1. @Component
  2. @PropertySource("classpath:website.properties")
  3. class WebSite {
  4. @Value("${url}")
  5. private String url;
  6. 省略getter/setter
  7. ......
  8. }

6. 参数校验

数据的校验的重要性就不用说了,即使在前端对数据进行校验的情况下,我们还是要对传入后端的数据再进行一遍校验,避免用户绕过浏览器直接通过一些 HTTP 工具直接向后端请求一些违法数据。
JSR(Java Specification Requests) 是一套 JavaBean 参数校验的标准,它定义了很多常用的校验注解,我们可以直接将这些注解加在我们 JavaBean 的属性上面,这样就可以在需要校验的时候进行校验了,非常方便!
校验的时候我们实际用的是 Hibernate Validator 框架。Hibernate Validator 是 Hibernate 团队最初的数据校验框架,Hibernate Validator 4.x 是 Bean Validation 1.0(JSR 303)的参考实现,Hibernate Validator 5.x 是 Bean Validation 1.1(JSR 349)的参考实现,目前最新版的 Hibernate Validator 6.x 是 Bean Validation 2.0(JSR 380)的参考实现。
SpringBoot 项目的 spring-boot-starter-web 依赖中已经有 hibernate-validator 包,不需要引用相关依赖。如下图所示(通过 idea 插件—Maven Helper 生成):
Spring/SpringBoot常见注解总结 - 图2
👉 需要注意的是: 所有的注解,推荐使用 JSR 注解,即javax.validation.constraints,而不是org.hibernate.validator.constraints

6.1 一些常用的字段验证的注解

  • @NotEmpty 被注释的字符串的不能为 null 也不能为空
  • @NotBlank 被注释的字符串非 null,并且必须包含一个非空白字符
  • @Null 被注释的元素必须为 null
  • @NotNull 被注释的元素必须不为 null
  • @AssertTrue 被注释的元素必须为 true
  • @AssertFalse 被注释的元素必须为 false
  • @Pattern(regex=,flag=)被注释的元素必须符合指定的正则表达式
  • @Email 被注释的元素必须是 Email 格式。
  • @Min(value)被注释的元素必须是一个数字,其值必须大于等于指定的最小值
  • @Max(value)被注释的元素必须是一个数字,其值必须小于等于指定的最大值
  • @DecimalMin(value)被注释的元素必须是一个数字,其值必须大于等于指定的最小值
  • @DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
  • @Size(max=, min=)被注释的元素的大小必须在指定的范围内
  • @Digits (integer, fraction)被注释的元素必须是一个数字,其值必须在可接受的范围内
  • @Past被注释的元素必须是一个过去的日期
  • @Future 被注释的元素必须是一个将来的日期
  • ……

    6.2 验证请求体(RequestBody)

    ```java @Data @AllArgsConstructor @NoArgsConstructor public class Person {

    @NotNull(message = “classId 不能为空”) private String classId;

    @Size(max = 33) @NotNull(message = “name 不能为空”) private String name;

    @Pattern(regexp = “((^Man$|^Woman$|^UGM$))”, message = “sex 值不在可选范围”) @NotNull(message = “sex 不能为空”) private String sex;

    @Email(message = “email 格式不正确”) @NotNull(message = “email 不能为空”) private String email;

}

  1. 我们在需要验证的参数上加上了@Valid注解,如果验证失败,它将抛出MethodArgumentNotValidException
  2. ```java
  3. @RestController
  4. @RequestMapping("/api")
  5. public class PersonController {
  6. @PostMapping("/person")
  7. public ResponseEntity<Person> getPerson(@RequestBody @Valid Person person) {
  8. return ResponseEntity.ok().body(person);
  9. }
  10. }

6.3 验证请求参数(Path Variables和Request Parameters)

一定一定不要忘记在类上加上 Validated 注解了,这个参数可以告诉 Spring 去校验方法参数。

  1. @RestController
  2. @RequestMapping("/api")
  3. @Validated
  4. public class PersonController {
  5. @GetMapping("/person/{id}")
  6. public ResponseEntity<Integer> getPersonByID(@Valid @PathVariable("id") @Max(value = 5,message = "超过 id 的范围了") Integer id) {
  7. return ResponseEntity.ok().body(id);
  8. }
  9. }