ToB企服应用市场:ToB评测及商务社交产业平台

标题: 《SpringBoot》史上最全SpringBoot干系注解先容 [打印本页]

作者: 羊蹓狼    时间: 2025-1-21 08:13
标题: 《SpringBoot》史上最全SpringBoot干系注解先容
@SpringBootApplication

@SpringBootApplication看作是 @Configuration、@EnableAutoConfiguration、@ComponentScan 注解的集合。
自动配置机制?在启动过程中,Spring Boot会扫描应用程序的类路径,根据定义条件匹配的各种AutoConfiguration类进行自动配置。通过条件化配置和默认属性值,根据应用程序的类路径和其他条件来自动配置Spring应用程序的各种组件。自动配置的目标是让开辟人员可以或许以最小的配置和干预自动获得功能完整的应用程序。
Spring Bean 干系

@Resource和@Autowired

两者的区别

@Autowired 是Spring框架提供的注解,重要用于根据范例自动装配依靠项。行为和特性:
@Resource 是JDK提供的注解,属于Java依靠注入规范(JSR-250)的一部分。行为和特性:
依靠注入的优先级(紧张)

在使用 @Resource 注解进行依靠注入时,优先级规则如下:
在使用 @Autowired 注解进行依靠注入时,优先级规则如下:
在使用 @Bean 方法中的参数 进行依靠注入时,默认的行为与 @Autowired 注解的工作方式是一致的。
@Component,@Repository,@Service, @Controller

一般使用 @Autowired 注解让 Spring 容器自动装配 bean。
但要想把类标识成可用于 @Autowired 注解自动装配的 bean 的类,可以采用以下注解实现:
@RestController

@RestController注解是@Controller和@ResponseBody的合集,体现这是个控制器 bean,并且是将函数的返回值直接填入 HTTP 响应体中,是 REST 风格的控制器,更加适合目前前后端分离的架构下,返回 JSON 数据格式。
单独使用 @Controller 不加 @ResponseBody的话一般是用在要返回一个视图的环境,这种环境属于比较传统的 Spring MVC 的应用,对应于前后端不分离的环境。@Controller +@ResponseBody 返回 JSON 或 XML 形式数据
@Scope

声明 Spring Bean 的作用域
常见的 Spring Bean 的作用域:
@Configuration

用来声明配置类,可以使用 @Component注解替换,不过使用@Configuration注解声明配置类更加语义化。
常见的 HTTP 哀求范例

5 种常见的哀求范例:
@RequestMapping 和 @GetMapping 注解的区别

@RequestMapping:可注解在类和方法上;@GetMapping 仅可注册在方法上
@RequestMapping:可进行 GET、POST、PUT、DELETE 等哀求方法;@GetMapping 是@RequestMapping 的GET哀求方法的特例
前后端传值

@PathVariable 和 @RequestParam

@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
@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. }
复制代码

读取配置信息

@Value

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

通过@ConfigurationProperties读取配置信息并与 bean 绑定。
@PropertySource(不常用)

@PropertySource读取指定 properties 文件
参数校验

详情可以看 优雅的参数校验
字段验证的注解

验证哀求体(RequestBody)

需要验证的参数上加上了@Valid注解,如果验证失败,它将抛出MethodArgumentNotValidException。
  1. @RestController
  2. @RequestMapping("/api")
  3. public class PersonController {
  4.     @PostMapping("/person")
  5.     public ResponseEntity<Person> getPerson(@RequestBody @Valid Person person) {
  6.         return ResponseEntity.ok().body(person);
  7.     }
  8. }
复制代码
验证哀求参数(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. }
复制代码
全局处理 Controller 层异常

一般推荐使用注解的方式统一异常处理,具领会使用到 @ControllerAdvice + @ExceptionHandler 这两个注解 。
  1. @ControllerAdvice
  2. @ResponseBody
  3. public class GlobalExceptionHandler {
  4.     @ExceptionHandler(BaseException.class)
  5.     public ResponseEntity<?> handleAppException(BaseException ex, HttpServletRequest request) {
  6.       //......
  7.     }
  8.     @ExceptionHandler(value = ResourceNotFoundException.class)
  9.     public ResponseEntity<ErrorReponse> handleResourceNotFoundException(ResourceNotFoundException ex, HttpServletRequest request) {
  10.       //......
  11.     }
  12. }
复制代码
这种异常处理方式下,会给所有大概指定的 Controller 织入异常处理的逻辑(AOP),当 Controller 中的方法抛出异常的时候,由被@ExceptionHandler 注解修饰的方法进行处理。
ExceptionHandlerMethodResolver 中 getMappedMethod 方法决定了异常具体被哪个被 @ExceptionHandler 注解修饰的方法处理异常。
[code]@Nullable  private Method getMappedMethod(Class




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4