Common annotations in SpringBoot (including usage examples) in detail (1)

A good memory is not as good as a bad pen, do you know all these annotations?

1. Spring Web MVC and Spring Bean annotations

  1. Spring Web MVC annotations

@RequestMapping

The @RequestMapping annotation is an annotation used to process request address mapping, which can be used to map a request or a method, and can be used on a class or method. The main purpose is to map web requests with methods in request processing classes.

Both Spring MVC and Spring WebFlux provide support for the @RequestMapping annotation through the RquestMappingHandlerMapping and RequestMappingHndlerAdapter classes.

The @RequestMapping annotation marks the request processing method in the request processing class;

The @RequestMapping annotation has the following six configuration properties:

  • value : the mapped request URL or its alias

  • method : HTTP-compatible method name

  • params: filter the request according to the village, default or value of the HTTP parameter

  • header: According to the village of HTTP Header, default or value to filter Qingqiu

  • consume: Set the media types allowed in the HTTP request file

  • product : the media types allowed in the HTTP response body

Tip: The request processing class needs to be marked with @Controller or @RestController before @RequestMapping

Here are two examples of using @RequestMapping:

@Controller
public class usercontroller {

    @RequestMapping(value = "/user/home",method = RequestMethod.GET)
    public  String   user(){

        System.out.println("hello word!");
        return  "/home";
    }

@RequestMapping can also mark the class, so that when the processing method in the class maps the request path, it will automatically splice the value set by @RequestMapping on the class before the mapping path in the method, as follows:

@RequestMapping("/user ")
@Controller
public class usercontroller {

    @RequestMapping(value = "/home",method = RequestMethod.GET)
    public  String   user(){

        System.out.println("hello word!");
        return  "/home";
    }

@RequestBody

@RequestBody is used in the parameter list of the processing request method, which can bind the parameters in the request body to an object,

请求主体参数是通过HttpMessageConverter传递的,根据请求主体中的参数名与对象的属性名进行匹配并绑定值。

此外,还可以通过@Valid注解对请求主体中的参数进行校验。

下面使用的@RequestBody的实例:

@RequestMapping("/user ")
@RestController
public class usercontroller {

    @Autowired //自动装配注解
    private UserService userService;

    @PostMapping("/users")
    public User create(@Valid @RequestBody User user) {
        return userService.save(user);
    }
}

@GetMapping

@GetMapping 注解用于处理HTTP GET请求,并将请求映射到具体的处理方法中具体来说就是, @GetMapping是一个组合注解,它相当于是@RequestMapping(method = RequestMethod.GET ) 快捷方式

下面是@GetMapping的一个实例

@PostMapping

@PostMapping注解用于处理HTTP POST请求,并将请求映射到具体的处理方法中。@PostMapping与@GetMapping一样,也是一个组合注解,它相当于是@RequestMapping(method=HttpMethod.POST)的快捷方式。

下面是@PostMapping简单使用方法

@PutMapping

@PutMapping注解用于处理HTTP PUT请求,并将请求映射到具体的处理方法中,@PutMapping是一个组合注解,相当于是@RequestMapping(method=HttpMethod.PUT)的快捷方式。

下面是使用@PutMapping的一个示例:

@DeleteMapping

@DeleteMapping注解用于处理HTTP DELETE请求,并将请求映射到删除方法中。@DeleteMapping是一个组合注解,它相当于是@RequestMapping(method=HttpMethod.DELETE)的快捷方式。

下面是使用@DeleteMapping的一个示例:

@PachMapping

@PatchMapping注解用于处理HTTP PATCH请求,并将请求映射到对应的处理方法中。@PatchMapping相当于是@RequestMapping(method=HttpMethod.PATCH)的快捷方式。

http method请求方式.常用的就是get post delete put;

Patch方式是对put方式的一种补充;

put方式是可以更新.但是更新的是整体.patch是对局部更新;

下面是一个简单的示例:

@ControllerAdvice

@ControllerAdvice是@Component注解的一个延伸注解,Spring会自动扫描并检测被@ControllerAdvice所标注的类。@ControllerAdvice需要和@ExceptionHandler@InitBinder以及@ModelAttribute注解搭配使用,主要是用来处理控制器所抛出的异常信息。

首先,我们需要定义一个被@ControllerAdvice所标注的类,在该类中,定义一个用于处理具体异常的方法,并使用@ExceptionHandler注解进行标记。

此外,在有必要的时候,可以使用@InitBinder在类中进行全局的配置,还可以使用@ModelAttribute配置与视图相关的参数。使用@ControllerAdvice注解,就可以快速的创建统一的,自定义的异常处理类。

下面是一个使用@ControllerAdvice的示例代码:

@ResponseBody

@ResponseBody会自动将控制器中方法的返回值写入到HTTP响应中。

特别的,@ResponseBody注解只能用在被@Controller注解标记的类中。如果在被@RestController标记的类中,则方法不需要使用@ResponseBody注解进行标注。

@RestController相当于是@Controller和@ResponseBody的组合注解。

下面是使用该注解的一个示例:

@ExceptionHandler

@ExceptionHander注解用于标注处理特定类型异常类所抛出异常的方法。当控制器中的方法抛出异常时,Spring会自动捕获异常,并将捕获的异常信息传递给被@ExceptionHandler标注的方法。

下面是使用该注解的一个示例:

@PathVariable

@PathVariable注解是将方法中的参数绑定到请求URI中的模板变量上。可以通过@RequestMapping注解来指定URI的模板变量,然后使用@PathVariable注解将方法中的参数绑定到模板变量上。

@Controller
@RequestMapping("hello")
public class HelloController2 {
    /**
     *3、占位符映射
     * 语法:@RequestMapping(value=”user/{userId}/{userName}”)
     * 请求路径:http://localhost:8080/hello/test/1/maomao
     * @param ids
     * @param names
     * @return
     */
    @RequestMapping("test/{id}/{name}")
    public ModelAndView test5(@PathVariable("id") Long ids ,@PathVariable("name") String names){
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg","占位符映射:id:"+ids+";name:"+names);
        mv.setViewName("tttttt");
        return mv;
    }
}

特别地,@PathVariable注解允许我们使用value或name属性来给参数取一个别名。

模板变量名需要使用{ }进行包裹,如果方法的参数名与URI模板变量名一致,则在@PathVariable中就可以省略别名的定义。

@ResponseStatus

@ResponseStatus注解可以标注请求处理方法。使用此注解,可以指定响应所需要的HTTP STATUS。特别地,我们可以使用HttpStauts类对该注解的value属性进行赋值。

下面是使用@ResponseStatus注解的一个示例:

@RequestParam

@RequestParam注解用于将方法的参数与Web请求的传递的参数进行绑定。

使用@RequestParam可以轻松的访问HTTP请求参数的值。

下面是使用该注解的代码示例:

该注解的其他属性配置与@PathVariable的配置相同,特别的,如果传递的参数为空,还可以通过defaultValue设置一个默认值。示例代码如下:

@Controller

@Controller@Component注解的一个延伸,

spring会自动扫描并配置被该注解标注的类。此注解用于标注Spring MVC的控制器。下面是使用此注解的示例代码:

@Controller
public class MyController {

    @RequestMapping ( "/showView" )
    public ModelAndView showView() {
       ModelAndView modelAndView = new ModelAndView();
       modelAndView.setViewName( "viewName" );
       modelAndView.addObject( " 需要放到 model 中的属性名称 " , " 对应的属性值,它是一个对象 " );
       return modelAndView;
    }

} 

@RestController

@RestController是在Spring 4.0开始引入的,这是一个特定的控制器注解。此注解相当于@Controller@ResponseBody的快捷方式。当使用此注解时,不需要再在方法上使用@ResponseBody注解。

下面是使用此注解的示例代码

@ModelAttribute

通过此注解,可以通过模型索引名称来访问已经存在于控制器中的model。下面是使用此注解的一个简单示例:

与@PathVariable和@RequestParam注解一样,如果参数名与模型具有相同的名字,则不必指定索引名称,简写示例如下:

特别地,如果使用@ModelAttribute对方法进行标注,Spring会将方法的返回值绑定到具体的Model上。示例如下:

在Spring调用具体的处理方法之前,被@ModelAttribute注解标注的所有方法都将被执行。

@CrossOrigin

@CrossOrigin注解将为请求处理类或请求处理方法提供跨域调用支持。如果我们将此注解标注类,那么类中的所有方法都将获得支持跨域的能力。使用此注解的好处是可以微调跨域行为。使用此注解的示例如下:

跨域@CrossOrigin源码

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CrossOrigin {
    @Deprecated
    String[] DEFAULT_ORIGINS = {"*"};

    @Deprecated
    String[] DEFAULT_ALLOWED_HEADERS = {"*"};

    @Deprecated
    boolean DEFAULT_ALLOW_CREDENTIALS = false;

    @Deprecated
    long DEFAULT_MAX_AGE = 1800;

    @AliasFor("origins")
    String[] value() default {};

    @AliasFor("value")
    String[] origins() default {};

    /**
     * @since 5.3
     */
    String[] originPatterns() default {};

    String[] allowedHeaders() default {};

    String[] exposedHeaders() default {};

    RequestMethod[] methods() default {};
    
    String allowCredentials() default "";

    long maxAge() default -1;
}

@InitBinder

@InitBinder注解用于标注初始化WebDataBinider的方法,该方法用于对Http请求传递的表单数据进行处理,如时间格式化、字符串处理等。下面是使用此注解的示例:

Guess you like

Origin blog.csdn.net/qq_60870118/article/details/129642165