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

【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办法,集成其余框架

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理