Spring中常用注解

一、@SpringBootApplication注解

@SpringBootApplication 注解是 Spring Boot项目的基石,创建SpringBoot项目后会默认在主类加上。

@SpringBootApplication
public class ExcelApplication {
    public static void main(String[] args) {
        SpringApplication.run(ExcelApplication.class, args);
    }
}

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

1、@SpringBootApplication底层代码:

package org.springframework.boot.autoconfigure;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.TypeExcludeFilter;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.core.annotation.AliasFor;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
    @AliasFor(
        annotation = EnableAutoConfiguration.class
    )
    Class<?>[] exclude() default {};

    @AliasFor(
        annotation = EnableAutoConfiguration.class
    )
    String[] excludeName() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackages"
    )
    String[] scanBasePackages() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackageClasses"
    )
    Class<?>[] scanBasePackageClasses() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "nameGenerator"
    )
    Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class;

    @AliasFor(
        annotation = Configuration.class
    )
    boolean proxyBeanMethods() default true;
}

2、@SpringBootConfiguration底层代码

package org.springframework.boot;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AliasFor;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
    @AliasFor(
        annotation = Configuration.class
    )
    boolean proxyBeanMethods() default true;
}

3、这三个注解作用:

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

二、Spring Bean 相关注解

1、@Autowired

自动导入对象到类中,被注入进的类同样要被 Spring 容器管理,如(service类要注入到 controller 类中)

@RestController
@RequestMapping("/user")
public class UserController{
  	@Autowired
  	private UserService userService;
}


@Service
public class UserServiceImpl implements UserService{
  
}

2、@Component,@Repository,@Service,@Controller

使用这些注解的类,可以用于 @Autowired 注解自动装配的 bean 的类。

@Component :通用注解,可标注任意类为 Spring 组件。如果一个 bean 不知道属于哪一层,可以使用此注解。

@Repository :持久层注解(Dao层),主要用于数据库的相关操作。

@Service :服务层注解,主要涉及一些复杂的逻辑,需要用到 Dao 层。

@Controller :控制层注解,主要用于接收用户请求并调用 Service 层代码返回数据给前端页面。

3、@RestController

@RestController 注解是 @Controller@ResponseBody 合集,表示这个是控制器 bean,并且是将控制层的返回值直接填入 HTTP 响应体中,是 REST 风格,返回 JSON 或 XML 形式数据,大多用于前后端分离应用中。

单独使用 @Controller 注解返回的是一个视图,这种情况大多用于传统 Spring MVC 的应用。

4、@Scope

@Scope 注解用于声明 Spring Bean 的作用域。

@Configuration
@Scope("singleton")
public class UserSingleton {
    @Bean
    public User userSingleton(){
        return new User();
    }
}

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

singleton:在 Sping Ioc 容器中仅存在一个 bean 实例,bean以单例方式存在,bean作用域范围的默认值。

prototype:每次从容器中调用 Bean 时,都返回一个新的实例。

request:每次 HTTP 请求都会创建一个新的 Bean,该 Bean 仅在当前 HTTP Request 内有效。

session:同一个 HTTP Session 共享一个 Bean,不同 Session 使用不同的 Bean。

5、@Configuration

@Configuration 注解用来声明配置类,可以使用 @Component 代替,但使用 @Configuration 更加语义化

@Configuration
public class ThreadConfig {
    @Bean
    public ThreadPoolTaskExecutor executor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(15);
        //配置最大线程数
        executor.setMaxPoolSize(30);
        //配置队列大小
        executor.setQueueCapacity(1000);
        //线程的名称前缀
        executor.setThreadNamePrefix("Executor-");
        //等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //执行初始化
        executor.initialize();
        return executor;
    }
}

三、处理常见HTTP请求类型注解

1、五种常见请求类型

  1. GET :请求从服务器获取特定资源。
  2. POST :向指定资源提交数据进行处理请求(例如提交表单或者上传文件)。数据被包含在请求体中,POST请求可能会导致新的资源的创建和/或已有资源的修改。
  3. PUT :向指定资源位置上传其最新内容。
  4. DELETE :请求服务器删除Request-URI所标识的资源。
  5. PATCH :更新服务器上的资源(客户端提供更改的属性,可以看做作是局部更新),使用的比较少。

2、GET请求

@GetMapping("getAll")
public ResponseEntity<List<User>> getAll(){
  	return userService.getAll();
}
// ResponseEntity不仅可以返回json结果,还可以定义返回的HttpStatus(状态码)和HttpHeaders(消息头:请求头和响应头)

3、POST请求

@PostMapping("/add")
public ResponseEntity<User> createUser(@RequestBody User user){
  	return userService.save(user);
}

4、PUT请求

@PutMapping("/getOne/{userId}")
public ResponseEntity<User> getOne(@PathVariable(value = "userId") Long userId) {
  	return userService.getOne(userId);
}

5、DELETE请求

@DeleteMapping("/delete/{userId}")
public ResponseEntity<User> delete(@PathVariable(value = "userId") Long userId){
  	return userService.delete(userId);
}

6、PATCH请求

@PatchMapping("/update")
public ResponseEntity update(@RequestBody User user){
  	return userService.update(user);
}

四、前后端传值注解

1、@PathVariable 和 @RequestParam

@PathVariable :用于获取路径参数。

@RequestParam :用于获取查询参数。

  • 语法:@RequestParam(value=”参数名”,required=”true/false”,defaultValue=””)
  • required:是否包含该参数,默认为true,表示该请求路径中必须包含该参数,如果不包含就报错。
  • defaultValue:默认参数值,如果设置了该值,required=true将失效,自动为false,如果没有传该参数,就使用默认值。
@GetMapping("/getOne/{userId}")
public List<User> getOne(@PathVariable(value = "userId") Long userId) {
  	return userService.list(userId);
}
/**
* 接收普通请求参数
* http://localhost:8080/hello/show16?name=linuxsir
* url参数中的name必须要和@RequestParam("name")一致
* @return
*/
@RequestMapping("show16")
public ModelAndView test16(@RequestParam("name")String name){
    ModelAndView mv = new ModelAndView();
    mv.setViewName("hello2");
    mv.addObject("msg", "接收普通的请求参数:" + name);
    return mv;
}

2、@RequestBody

用于读取 Request 请求(可能是POST、PUT、DELETE、GET请求)的 body 部分并且 Content-Type 为application/json 格式的数据,接收到数据之后会自动将数据绑定到 JavaBean 对象上。

@PostMapping("/couponAdd")
public Results Add(@RequestBody User model) {
    boolean response = userService.save(model);
    //自定义的返回类型
    Results results = Results.success(response);
    return results;
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IbepawRC-1592472923362)(/1.png)]

注意:一个请求方法只可以有一个@RequestBody,但是可以有多个@RequestParam和@PathVariable

五、读取配置信息注解

1、概述

很多时候我们需要将一些配置信息放到配置文件中(如:application.yml文件)

age: 18
woman:
  name: "张三"
  age: 18

2、@Value(常用)

语法:

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

示例:

@Value("${age}")
private Integer age;

3、@ConfigurationProperties(常用)

@ConfigurationProperties:读取配置信息并与 Bean 绑定。

@Component
@ConfigurationProperties(prefix = "mybatis-plus")
class MybatisPlusProperties{
  	private String name;
  	private Integer age;
  	省略getter/setter
    ...
}

六、参数校验注解

1、概述

数据的校验很重要,即使在前端做了数据校验,但还是要对传入后端的数据再进行一遍校验,避免用户绕过浏览器直接通过一些 HTTP 工具直接向后端请求一些违法数据。

JSR(Java Specification Requests)是一套 JavaBean 参数校验的标准,它定义了很多常用的校验注解,我们可以直接将这些注解加在我们的 JavaBean 的属性上面,这样就能在需要校验的时候进行校验。

SpringBoot 项目的 spring-boot-starter-web 依赖中已经有 hibernate-validator 包,不需要引用相关依赖。

所有的注解推荐使用 JSR 注解,即 javax.validation.constraints 不是 org.hibernate.validator.constraints

2、一些常用字段验证注解

@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 :被注释的元素必须是一个将来的日期。

3、验证请求体(RequestBody)

@Data
@AllArgsConstructor
@NoArgsConstructorpublic 
public class User {    
    @NotNull(message = "classId 不能为空")    
    private String id;    
    @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;
}

使用时需要在验证的参数上加上 @Valid 注解,如果校验失败,抛出 MethodArgumentNotValidException 异常。

@RestController
@RequestMapping("/user")
public class UserController {    
    @PostMapping("/getOne")    
    public ResponseEntity<User> getUser(@RequestBody @Valid User user) {        
      	return ResponseEntity.ok().body(user);    
    }
}

4、验证请求参数(PathVariables 和 RequestParameters)

需要在控制层上加 @Validated 注解,作用是告诉 Spring 去校验方法参数。

@RestController
@RequestMapping("/api")
@Validated
public class UserController {    
  @GetMapping("/user/{id}")    
  public ResponseEntity<Integer> getId(@Valid @PathVariable("id") @Max(value = 5,message="超过id的范围了") Integer id) {        
    	return ResponseEntity.ok().body(id);
  }
}

七、全局处理 Controller 层异常注解

相关注解:

@ControllerAdvice :定义全局异常处理类

@ExceptionHandler :声明异常处理方法

定义全局异常处理类:

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler{
  	// 会处理所有controller层抛出的Exception及其子类的异常
  	@ExceptionHandler(Exception.class)
    public String handleException(){
      	return "Exception";
    }
}

@ExceptionHandler 注解中未声明异常类型,则可以改写为:

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler{
  	// 会处理所有controller层抛出的Exception及其子类的异常
  	@ExceptionHandler()
    public String handleException(Exception e){
      	return "Exception" + e.getMessage();
    }
}

八、事务注解

@Transactional :开启事务处理。

作用范围:一般用在 或者 方法 上。

  • 作用在类上:表示该类的所有 public 方法都配置事务处理。
  • 作用在方法:当类上有注解,方法上也有注解,那么方法上的注解会覆盖类上的注解。

注意:Exception 分为运行时异常 RuntimeException 和非运行时异常。在@Transactional注解中如果不配置rollbackFor属性,那么事物只会在遇到RuntimeException的时候才会回滚,加上rollbackFor=Exception.class,可以让事物在遇到非运行时异常时也回滚。

@Transactional(rollbackFor = Exception.class)
public void save() {
  ......
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值