Java注解配置rest服务_SpringBoot——构建一个RESTful Web服务

1. 使用@RestController注解

@RestController 相当于 @ResponseBody + @Controller的结合

2. 使用@RequestMapping注解

这个注解会将 HTTP 请求映射到 MVC 和 REST 控制器的处理方法上。

3.使用@RequestParam注解

用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容。(Http协议中,如果不指定Content-Type,则默认传递的参数就是application/x-www-form-urlencoded类型)

RequestParam可以接受简单类型的属性,也可以接受对象类型。

实质是将Request.getParameter() 中的Key-Value参数Map利用Spring的转化机制ConversionService配置,转化成参数接收对象或字段。

4.使用@SpringBootApplication注解

@SpringBootApplication是一个组合注解,包括@EnableAutoConfiguration, @Configuration 和@ComponentScan。

下面是demo:

Greeting.java

public class Greeting {

private final long id;

private final String content;

public Greeting(long id, String content) {

this.id = id;

this.content = content;

}

public long getId(){

return id;

}

public String getContent(){

return content;

}

}

GreetingController.java

@RestController

public class GreetingController {

private static final String template = "Hello, %s";

private final AtomicLong couter = new AtomicLong();

@RequestMapping("/greeting")

public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {

return new Greeting(couter.incrementAndGet(),String.format(template,name));

}

}

Application.java

@SpringBootApplication

public class Application {

public static void main(String[] args) {

SpringApplication.run(Application.class, args);

}

}

结果:{"id":1,"content":"Hello, World!"}

你可能感兴趣的:(Java注解配置rest服务)