spring-boot构建RESTful Web服务

往后官方demo的笔记不贴代码了,只贴链接

官方文档

RESTful Web服务

该服务将处理GET请求/greeting,可选地使用name查询字符串中的参数。该GET请求应该返回200 OK在表示问候的身体与JSON响应。它应该看起来像这样:

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

浏览器输入localhost:8080/greeting,成功返回,如下:


学习要点

  1. @RestController

    • 在Spring构建RESTful Web服务的方法中,HTTP请求由控制器处理。这些组件很容易通过@RestController注释来识别.
    • Spring 4的新@RestController注释,它将类标记为控制器,其中每个方法都返回一个域对象而不是视图。它是速记@Controller和@ResponseBody拼凑在一起的。
    • @RequestMapping注释可以确保HTTP请求/greeting被映射到greeting()方法。
    • @RequestParam将查询字符串参数的值绑定name到方法的name参数中greeting()。如果name请求中不存在该参数,defaultValue则使用“World”。
  2. @SpringBootApplication注解(谷歌翻译)

    • @SpringBootApplication 是一个便利注解,添加了以下所有内容:

      • @Configuration 标记该类作为应用程序上下文的bean定义的源。

      • @EnableAutoConfiguration 告诉Spring Boot开始根据类路径设置,其他bean和各种属性设置添加bean。

      • 通常你会添加@EnableWebMvc一个Spring MVC应用程序,但Spring Boot会在类路径上看到spring-webmvc时自动添加它。这会将应用程序标记为Web应用程序并激活关键行为,例如设置a DispatcherServlet。

      • @ComponentScan告诉Spring在包中寻找其他组件,配置和服务hello,允许它找到控制器。

    • 该main()方法使用Spring Boot的SpringApplication.run()方法来启动应用程序。您是否注意到没有一行XML?也没有web.xml文件。此Web应用程序是100%纯Java,您无需处理配置任何管道或基础结构。


最后,GreetingController中还有一个类:java.util.concurrent.atomic.AtomicLong

放代码吧

package hello;

import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }
}

new AtomicLong();new 了一个counter对象,初始值为0,而后在new greeting的时候作为greeting类的id传入时,调用了incrementAndGet()方法,该方法会将原来的值+1后返回。
可参考:java se 7

END

猜你喜欢

转载自www.cnblogs.com/famine/p/10071506.html