第一个 Spring Boot 程序 : 构建 RESTful 服务

把我们基础的项目来升级一点点,还是照着文档来 https://spring.io/guides/gs/rest-service/

web.xml 没有变化

项目分成了几个包


第一个 Spring Boot 程序 : 构建 RESTful 服务_第1张图片

 实体类 Greeting


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;
	}

}

controller


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;

import com.lzf.bean.Greeting;

@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));
	}
}


 main 函数


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

@SpringBootApplication
public class Application {

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

}

运行

http://localhost:8080/greeting   ---->   {"id":1,"content":"Hello, World !"}

http://localhost:8080/greeting?name=user  ---> {"id":2,"content":"Hello, user !"}


确实方便,没写一个xml

你可能感兴趣的:(spring-boot)