SpringBoot注解大全

本文介绍了Spring及Spring Boot的常用注解。如@SpringBootApplication是主配置类复合注解,可由@ComponentScan等三个注解代替;@ResponseBody用于异步获取数据构建RESTful api;还有@RequestMapping等注解,说明了它们的作用、使用场景及相关属性设置。

@SpringBootApplication

该注解为SpringBoot主配置类的注解,为复合注解,查找源码可以发现该注解包含

包含了@ComponentScan@Configuration@EnableAutoConfiguration注解,可以用这个三个注解代替该注解。

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

//使用三种注解代替@SpringBootApplication复合注解
@EnableAutoConfiguration
@Configuration
@ComponentScan
public class DemoApplication {
	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

@ResponseBody

表示该方法的返回结果直接写入HTTP response body中,一般在异步获取数据时使用,用于构建RESTful的api。该注解一般会配合@RequestMapping一起使用

@Controller

用于定义控制器类,在spring项目中由控制器负责将用户发来的URL请求转发到对应的服务接口(service层)

@RestController

用于标注控制层组件(如struts中的action),@ResponseBody和@Controller的合集

@RequestMapping

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

@RequestMapping(path="/test",method=RequestMethod.GET,produces="application/json;charset=utf-8",params={"name","city"})

Method定义其请求方式GET,Post,Put,Delete.

Produces:设置返回值类型还可以设定返回值的字符编码

Path:指定访问路径

Value:指定访问路径,和Path作用相同

Consumes:定指定处理请求的 提交内容类型 (Content-Type)例application/json, text/html

Params:指定request中必须包含某些参数值时,才让该方法处理

 

@GetMapping = @RequestMapping(method = RequestMethod.GET)

@PostMapping = @RequestMapping(method = RequestMethod.POST)

@PutMapping = @RequestMapping(method = RequestMethod.PUT)

@DeleteMapping = @RequestMapping(method = RequestMethod.DELETE)

@Service

一般用于修饰service层的组件

@Repository

用于定义(到)数据处理层

@Autowired

自动导入依赖的bean

@ComponentScan

让spring Boot扫描到Configuration类并把它加入到程序上下文。

@Configuration

等同于spring的XML配置文件;使用Java代码可以检查类型安全。

@EnableAutoConfiguration

自动配置。

 

@PathVariable:

定义路径变量:@RequestMapping(path = "/{depid}/{userid}", method = RequestMethod.GET) 可以同时指定多个提交方法

getUser(@PathVariable("depid") String departmentID,@PathVariable("userid") String userid)

@RequestBody

处理HttpEntity传递过来的数据。GET方式无请求体,所以使用@RequestBody接收数据时,前端不能使用GET方式提交数据,而是用POST方式进行提交。

@RequestMapping(value="/testuser",method=RequestMethod.POST)
	public Object RequestParams(@RequestBody User user){
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("user", user);
		return params;
	}

 

@RequestParam

将请求参数绑定到你控制器的方法参数上

 该注解有三个属性:

(1)value:请求参数名(必须配置)

(2)required:是否必需,默认为 true,即 请求中必须包含该参数,如果

没有包含,将会抛出异常(可选配置)

(3)defaultValue:默认值,如果设置了该值,required 将自动设为 false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值