Spring Boot 入门

最简单的SpringBoot应用

首先使用maven添加依赖

POM.XML



    4.0.0

    com.tw.josaber
    todo-list-api
    1.0-SNAPSHOT

    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.7.RELEASE
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
    


添加Controller

HelloController.java

package com.tw.josaber;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@EnableAutoConfiguration
public class HelloController {

    @RequestMapping("/")
    @ResponseBody
    String hello() {
        return "Hello World!";
    }
}

Spring boot 启动入口

Application.java

package com.tw.josaber;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

启动应用

mvn spring-boot:run
访问http://localhost:8080


为了进一步地学习Spring boot,我们来实现TodoListApi

GitHub地址: TodoListApi

结果如下

GET

$ curl -X GET "http://localhost:8080/todoitems" -H "accept: application/json"
...
{"items":[{"id":1,"text":"finish todo list","done":false,"timestamp":"2011-01-21T11:33:21Z"},{"id":2,"text":"finish the homework","done":true,"timestamp":"2011-01-21T11:33:21Z"},{"id":3,"text":"This is for test create.","done":true,"timestamp":"2017-01-20T16:23:05Z"}]}%

POST

$ curl -X POST "http://localhost:8080/todoitems" -H "accept: application/json" -H "Content-Type: application/json" -d "{ \"text\": \"string\"}"
...
{"status":201,"message":"Create Todo Item Successfully!","todoItem":{"id":4,"text":"string","done":false,"timestamp":"2017-09-25T21:46:25Z"}}%

PUT

$ curl -X PUT "http://localhost:8080/todoitems/1" -H "accept: application/json" -H "Content-Type: application/json" -d "{ \"text\": \"string\", \"done\": true}"
...
{"status":200,"message":"Update Todo Item Successfully!","todoItem":{"id":1,"text":"string","done":true,"timestamp":"2017-09-25T21:52:34Z"}}%

$ curl -X PUT "http://localhost:8080/todoitems/5" -H "accept: application/json" -H "Content-Type: application/json" -d "{ \"text\": \"string\", \"done\": true}"
...
{"status":404,"message":"The Todo Item Is Not Found!","todoItem":null}%

DELETE

$ curl -X DELETE "http://localhost:8080/todoitems/1" -H "accept: application/json"

$ curl -X DELETE "http://localhost:8080/todoitems/100" -H "accept: application/json"
...
{"status":404,"message":"Fail to Delete Todo Item!","todoItem":null}%

参考

https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/

你可能感兴趣的:(Spring Boot 入门)