关于springboot:SpringBoot常用注解个人整理

4次阅读

共计 10906 个字符,预计需要花费 28 分钟才能阅读完成。

【Spring Web MVC】

Request

@RequestMapping

提供路由信息,负责 URL 到 Controller 中具体函数的映射。

@GetMapping 👈

GET 申请:从服务器获取特定资源。
@GetMapping(“/blog”)相当于 @RequestMapping(value=”/blog”,method=RequestMethod.GET)

@PostMapping 👈

POST 申请:在服务器上创立一个新的资源。
@PostMapping(“/blogs/save”)等价于 @RequestMapping(value=”/blog/save”,method=RequestMethod.POST)

consumes属性用于指定申请输出,而 produces 用于指定申请输入。

@PostMapping(consumes="application/json")
    @ResponseStatus(HttpStatus.CREATED)
    public Taco postTaco(@RequestBody Taco taco) {return tacoRepo.save(taco);
    }

@PutMapping

PUT 申请:更新服务器上的资源,客户端提供更新后的整个资源。

@DeleteMapping

DELETE 申请:从服务器删除特定的资源

@PatchMapping

PATCH 申请:更新服务器上的资源,客户端提供更改的属性,能够看作为局部更新


params

@PathVariable 👈

获取门路参数,从 url 模板里取值,接管申请门路中占位符的值。

比方:

 @GetMapping("/blog/{id}")
 public Result detail(@PathVariable(name = "id") Long id){Blog blog = blogService.getById(id);
     return Result.succ200(blog);
}

@RequestParam 👈

获取查问参数,从 request 里拿数据。

@GetMapping("/blog") // 分页解决
public Result list(@RequestParam(defaultValue = "1") Integer currentPage){Page page = new Page(currentPage,5);
   IPage pageData = ……
   return Result.succ200(pageData);
}

这里前端的代码是这样的:

_this.$axios.get("/blog?currentPage=" + currentPage)

@RequestParam 反对上面四种参数

  • defaultValue 如果本次申请没有携带这个参数,或者参数为空,那么就会启用默认值
  • name 绑定本次参数的名称,要跟 URL 下面的一样
  • required 这个参数是不是必须的
  • value 跟 name 一样的作用,是 name 属性的一个别名

@RequestBody 👈

用于读取 Request 申请的 body 局部,并且 ContentType 为 application/json 格局的数据,接管到数据后会主动将数据绑定到 Java 对象上。零碎会应用 HttpMessageConverter(或者本人定义) 将申请的 body 中的 json 字符串转换为 java 对象。

@RequiresAuthentication // 须要认证之后能力拜访
@PostMapping("/blog/edit")
public Result edit(@Validated @RequestBody Blog blog) {
    Blog temp = null;
    if(blog.getId() != null) {……

一个申请办法只能够有一个 @RequestBody,然而能够有多个 @RequestParam 和 @PathVariable。

@ModelAttribute

@ModelAttribute 标注可被利用在办法或办法参数上。

标注在办法上的 @ModelAttribute 阐明办法是用于增加一个或多个属性到 model 上。这样的办法能承受与 @RequestMapping 标注雷同的参数类型,只不过不能间接被映射到具体的申请上。

@CrossOrigin

容许来自任何域的客户端生产该 API

@RestController  //REST 控制器
@RequestMapping(path="/design",produces="application/json")
@CrossOrigin(origins="*")  // 容许跨域申请
public class DesignTacoController {
    private TacoRepository tacoRepo;
    @Autowired
    EntityLinks entityLinks;
    public DesignTacoController(TacoRepository tacoRepo) {this.tacoRepo = tacoRepo;}
    ……

@Controller

对应 Spring MVC 管制层,次要用于接管用户申请并调用 Service 层提供的性能返回数据给前端。

@RestController 👈

@RestController注解:
相当于 @Controller+@ResponseBody 两个注解的联合。

返回 json 数据不须要在办法后面加 @ResponseBody 注解了,但应用 @RestController 这个注解,就不能返回 jsp,html 页面,视图解析器无奈解析 jsp,html 页面。

该注解将函数的返回值间接填入 HTTP 响应体,是 REST 格调的控制器。


@ControllerAdvice

定义全局异样解决类。蕴含 @Component。

@RestControllerAdvice


@InitBinder

@InitBinder 用于在 @Controller 中标注于办法,示意为以后控制器注册一个属性编辑器或者其余,只对以后的 Controller 无效。


Response

@ResponseStatus

@ResponseStatus(HttpStatus.CREATED)
@ResponseStatus(HttpStatus.UNAUTHORIZED) //401 没有权限
    @ExceptionHandler(value = ShiroException.class)
    public Result handler(ShiroException e){log.error("没有权限");
        return Result.succ(401,e.getMessage(),null);
    }

@ResponseBody

示意该办法的返回后果间接写入 HTTP response body 中,个别在异步获取数据时应用,用于构建 REST 格调的 api。

在应用 @RequestMapping 后,返回值通常解析为跳转门路,加上 @ResponseBody 后返回值不会被解析为跳转门路,而是间接写入 HTTP response body 中。

@ExceptionHandler

申明异样解决办法。

/**
 * 全局异样解决
 */
@Slf4j
@RestControllerAdvice //@RestControllerAdvice 都是对 Controller 进行加强的,能够全局捕捉 spring mvc 抛的异样
public class GlobalExceptionHandler {@ResponseStatus(HttpStatus.UNAUTHORIZED) //401 没有权限
    @ExceptionHandler(value = ShiroException.class)
    public Result handler(ShiroException e){log.error("没有权限");
        return Result.succ(401,e.getMessage(),null);
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = RuntimeException.class)
    public Result handler(RuntimeException e){log.error("运行时异样");
        return Result.succ400(e.getMessage());
    }

【Spring Bean】

@ComponentScan

见 Spring Boot 局部。

@Component

通用的注解,可标注任意类为 Spring 组件。当一个 Bean 难以明确为哪个层时,能够应用这个。

@Service

对应服务层,次要波及一些逻辑。

@Repository

对应长久层 Dao 层,罕用于数据库相干。

@Bean 👈

办法级别上的注解,次要用在 @Configuration 或 @Component 注解的类里

  • @Bean 注解作用在办法上
  • @Bean 批示一个办法返回一个 Spring 容器治理的 Bean
  • @Bean 办法名与返回类名统一,首字母小写
  • @Bean 个别和 @Component 或者 @Configuration 一起应用
  • @Bean 注解默认作用域为单例 singleton 作用域,可通过 @Scope(“prototype”) 设置为原型作用域

默认状况下 Bean 名称就是办法名

@Bean
public MyBean myBean() {return new MyBean();
}

@Bean 注解反对设置别名,myBean1 和 myBean 都能够用

@Bean("myBean1")
public MyBean myBean() {return new MyBean();
}

能够通过 @Bean 注解的 initMethod 和 destrodMethod 进行指定 Bean 在初始化和销毁时须要调用相应的办法,相当于 XML 文件 bean 标签里的:init-method 和 destroy-method–> <bean id="personService" class="com.myapp.core.beanscope.PersonService" scope="singleton" init-method="init" destroy-method="cleanUp">

public class MyBean {public void init() {System.out.println("MyBean 开始初始化...");
    }
 
    public void destroy() {System.out.println("MyBean 销毁...");
    }
 
    public String get() {return "MyBean 应用...";}
}
@Bean(initMethod="init", destroyMethod="destroy")
public MyBean myBean() {return new MyBean();
}

@Scope

申明 Spring Bean 的作用域

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

这里 singleton 其实是 Spring Bean 的默认作用域。


【容器配置】

@Autowired 👈

主动导入对象到类中,被注入进的类同样要被 Spring 容器治理,比方:Service 类注入到 Controller 类中。

@Service
public class XxxService{ }

@Controller
public class xxxController{
    @Autowired
    private XxxService xxxService;
}

@Autowired 能够对 类成员变量 办法 以及 构造方法 进行标注,让 Spring 实现 Bean 主动拆卸的工作。
默认是依照类去匹配,配合 @Qualifier 按指定名称去拆卸 bean

想把类标识为可用于 @Autowired 注解主动拆卸的 Bean 类,能够应用 @Component、@Repository、@Service、@Controller 注解润饰类。

  • @Autowired(required=true):当应用 @Autowired 注解的时候,其实默认就是 @Autowired(required=true),示意注入的时候,该 bean 必须存在,否则就会注入失败。
  • @Autowired(required=false):示意疏忽以后要注入的 bean,如果有间接注入,没有跳过,不会报错。
  • @Autowired 在构造函数上
    首先让咱们在构造函数上应用 @Autowired。咱们将看到 SampleServiceSpring 将其注入到 AutowireDITestService.

    @Component
    public class SampleService {public void sample() {System.out.println("Sample Service");
    }
    }
@Component
public class AutowireDITestService {
  
        // ...
  private SampleService sampleService;
  
  @Autowired
  public AutowireDITestService(SampleService sampleService) {this.sampleService = sampleService;}
  
        // ...  
}
  • 在 setter 办法上增加 @Autowired
    在以下示例中,setter 办法 ExampleService 在 AutowireDITestService 创立时应用实例调用。
@Component
public class ExampleService {public void example() {System.out.println("Example Service");
  }
}
@Component
public class AutowireDITestService {
        // ...
  private ExampleService exampleService;
  
  @Autowired
  public void setExampleService(ExampleService exampleService) {this.exampleService = exampleService;}
        // ...  
}
//We can also apply @Autowired on methods with any number of arguments.
@Component
public class AutowireCustomMethodDITestService {

  private DemoService demoService;
  private ExampleService exampleService;
  private SampleService sampleService;
  
  @Autowired
  public void initialize(DemoService demoService, ExampleService exampleService, SampleService sampleService) {
    this.demoService = demoService;
    this.exampleService = exampleService;
    this.sampleService = sampleService;
  }
  // ...
}
  • 在属性上应用 @Autowired
    这样咱们就能够防止主动拆卸属性的 setter 和 getter。
package com.javabydeveloper.spring.autowire.service;

@Component
public class DemoService {public void demo() {System.out.println("Demo Service");
  }
}
@Component
public class AutowireDITestService {

  // @Autowired on property
  @Autowired
  private DemoService demoService;

        // ...
}
  • 从 5.0 开始,Spring 反对对单个办法和结构函数参数进行 @Autowired 注解。但外围 Spring Framework 中惟一被动反对主动拆卸参数的局部是 spring-test 模块中的 JUnit Jupiter 反对。
@SpringJUnitConfig(AppConfigForAutowired.class)
class AutowireParametersTest {

  private SampleService sampleService;

  // @Autowired on constructor parameters
  AutowireParametersTest(@Autowired SampleService sampleService) {this.sampleService = sampleService;}

  // @Autowired on method parameters
  @Test
  void injectServicesTest(@Autowired DemoService demoService,
      @Autowired(required = true) ExampleService exampleService) {demoService.demo();
    exampleService.example();
    sampleService.sample();}
}

@Primary

当一个接口有 2 个不同实现时, 应用 @Autowired 注解时会报 org.springframework.beans.factory.NoUniqueBeanDefinitionException 异样信息,

Primary 能够了解为默认优先选择, 不能够同时设置多个, 外部本质是设置 BeanDefinition 的 primary 属性。


@PostConstruct

当咱们在 Spring Bean 中应用 @PostConstruct 注解注解一个办法时,它会在 Spring bean 初始化后执行。

咱们只能用 @PostConstruct 注解来注解一种办法。这个注解是 Common Annotations API 的一部分,也是 JDK 模块的一部分 javax.annotation-api。因而,如果您在 Java 9 或更高版本中应用此正文,则必须显式地将此 jar 增加到您的我的项目中。如果您应用的是 maven,则应向其中增加以下依赖项。

<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.2</version>
</dependency>

如果您应用的是 Java 8 或更低版本,则无需增加上述依赖项。


@PreDestroy

When we annotate a Spring Bean method with PreDestroy annotation, it gets called when bean instance is getting removed from the context.

This is a very important point to understand – if your spring bean scope is“prototype”then it’s not completely managed by the spring container and PreDestroy method won’t get called.


@Qualifier

当有多个同一类型的 Bean 时,能够用 Qualifier(“name”)来指定。与 @Autowired 配合应用。


【Spring Boot】

Conditional 条件拆卸

Spring 4.0 增加的新注解,用来标识一个 Spring Bean 或者 Configuration 配置文件,当满足指定的条件才开启配置。

按条件注册 Bean

  • @ConditionalExpression
  • @ConditionalOnNotWebApplication
  • @ConditionalOnWebApplication
  • @ConditionalOnResource
  • @ConditionalOnProperty
  • @ConditionalOnMissingBean
  • @ConditionalOnBean
  • @ConditionalOnMissingClass
  • @ConditionalOnClass


    @SpringBootApplication

    @SpringBootApplication主动加载所有配置文件并扫描以后包及其子包中的组件。

SpringBoot 我的项目的基石,创立 SpringBoot 我的项目之后会默认在主类加上,标识这是一个 SpringBoot 利用。

是 @SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan 这三个注解的组合

@ComponentScan

Spring 3.1 增加的注解,用来代替配置文件中的 component-scan 配置,开启组件扫描。
主动扫描包门路下的 @Component 注解进行注册 bean 实例到 context 中。

扫描被 @Component(@Service,@Controller)注解的 bean,注解默认会扫描 该类所在包 下所有的类。

@EnableAutoConfiguration

启用 SpringBoot 的主动配置机制,开启这个注解之后,SpringBoot 就能依据以后类门路下的包或者类来配置 Spring Bean。

@AutoConfigurationPackage

@SpringBootConfiguration

@Configuration 注解的变体,只是用来润饰是 SpringBoot 配置而已。

@Configuration 👈

等同于 Spring 的 XML 配置文件里的 <Beans\> 标签
@Bean 能够了解为用 Spring 时的 <Bean\>

在 @Configuration 类中被 @Bean 标注的办法会被 Spring 进行 CGLIB 代理,从而进行加强。

容许在 Spring 上下文中注册额定的 bean 或导入其余配置类

用于申明 配置类,能够应用 @Component 注解代替。
Configuration 的两种配置

Full 模式:@Configuration(proxyBeanMethods = true) 全模式
Lite 模式:@Configuration(proxyBeanMethods = false) 轻量级模式


【读取配置信息】

@value ⚙

读取简略的配置信息。
假如 yml 文件里有 car: 巴拉巴拉

@Value("${car}")
String car;

@ConfigurationProperties ⚙

用来加载额定的配置(如.properties 文件),可用在 @Configuration 注解类、或 @Bean 注解办法上。

@Component:注入到容器中作为组件
@ConfigurationProperties:和配置文件绑定



@EnableConfigurationProperties ⚙

肯定要配合 @ConfigurationProperties 注解应用,用来开启 @ConfigurationProperties 注解配置 Bean 的反对。

@EnableConfigurationProperties:开启指定类的属性配置性能,并且注入到容器中

和配置文件绑定还是要绑定的。


【参数校验】

JSR是一套 JavaBean 参数校验的规范,定义了很多罕用的校验注解,能够将注解间接加在 Java Bean 的属性上。

校验时理论用的是 Hibernate Validator 框架。
SpringBoot 我的项目中的 spring-boot-starter-web 依赖中曾经有 hibernate-validator 包,不须要引入依赖。

应用注解的时候,举荐 import 的是:

import javax.validation.constraints.xxxx;
  • @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 被正文的元素必须是一个未来的日期
……
import javax.validation.constraints.NotBlank;

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("m_blog")
public class Blog implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    private Long userId;

    @NotBlank(message = "题目不能为空")
    private String title;

    @NotBlank(message = "摘要不能为空")
    private String description;

    @NotBlank(message = "内容不能为空")
    private String content;

    // 这里工夫在前端显示的格局不太称心,加个注解
    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDateTime created;

    private Integer status;

}

【Spring Cloud】

@SpringCloudApplication

@EnableDiscoveryClient

@SpringBootApplication


罕用配合

  • @Controller 类 + @Autowired 属性(Service 类)
  • @Configuration 类 + @Bean 办法,集成其余框架
正文完
 0