1. Controller & RequestMapping
@Controller用来标注在类上,表示这个类是一个控制器类,可以用来处理http请求,通常会和@RequestMapping一起使用。这个注解上面有@Component注解,说明被@Controller标注的类会被注册到spring容器中,value属性用来指定这个bean的名称
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
@AliasFor(
annotation = Component.class
)
String value() default "";
}
@RequestMapping表示请求映射,一般用在我们自定义的Controller类上或者Controller内部的方法上。
通过这个注解指定配置一些规则,满足这些规则的请求会被标注了@RequestMapping的方法处理。
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
String name() default "";
/**
* 限制url
*/
@AliasFor("path")
String[] value() default {};
/**
* 限制url
*/
@AliasFor("value")
String[] path() default {};
/**
* 限制http请求的method
*/
RequestMethod[] method() default {};
/**
* 限制请求的参数
*/
String[] params() default {};
/**
* 限制请求头
*/
String[] headers() default {};
/**
* 限制Content-Type的类型(客户端发送数据的类型)
*/
String[] consumes() default {};
/**
* 限制Accept的类型(客户端可接受数据的类型)
*/
String[] produces() default {};
}
可以简化@RequestMapping的注解如下:
注解 |
相当于 |
@PostMapping |
@RequestMapping(method=RequestMethod.POST) |
@GetMapping |
@RequestMapping(method=RequestMethod.GET) |
@DeleteMapping |
@RequestMapping(method=RequestMethod.DELETE) |
@PutMapping |
@RequestMapping(method=RequestMethod.PUT) </ |