[关闭]
@xtccc 2016-12-21T00:58:56.000000Z 字数 2188 阅读 2035

Spring Boot Tutorial

给我写信
GitHub

此处输入图片的描述

Spring Boot


目录:


1. 简单的REST API Server代码


SampleController.java

  1. package cn.gridx.springboot.web;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.boot.SpringApplication;
  5. import org.springframework.boot.autoconfigure.SpringBootApplication;
  6. import org.springframework.web.bind.annotation.*;
  7. import java.util.concurrent.atomic.AtomicLong;
  8. @SpringBootApplication
  9. @RestController
  10. public class SampleController {
  11. Logger logger = LoggerFactory.getLogger(this.getClass());
  12. private static final String template = "Hello, %s!";
  13. private final AtomicLong counter = new AtomicLong();
  14. @RequestMapping(method = RequestMethod.GET, path = "/home")
  15. public String home() throws InterruptedException {
  16. logger.info("[home] 收到请求");
  17. Thread.sleep(10*1000);
  18. logger.info("[home] 返回响应");
  19. return "Hello World!";
  20. }
  21. @RequestMapping(method = RequestMethod.GET, path = "/greeting")
  22. public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name)
  23. throws InterruptedException {
  24. logger.info("[greeting] 收到请求");
  25. Thread.sleep(10*1000);
  26. logger.info("[greeting] 返回响应");
  27. return new Greeting(counter.incrementAndGet(),
  28. String.format(template, name));
  29. }
  30. public static void main(String[] args) throws Exception {
  31. SpringApplication.run(SampleController.class, args);
  32. }
  33. }



Greeting.java

  1. package cn.gridx.springboot.web;
  2. public class Greeting {
  3. private final long id;
  4. private final String content;
  5. public Greeting(long id, String content) {
  6. this.id = id;
  7. this.content = content;
  8. }
  9. public long getId() {
  10. return id;
  11. }
  12. public String getContent() {
  13. return content;
  14. }
  15. }



build.gradle

  1. buildscript {
  2. repositories {
  3. mavenCentral()
  4. }
  5. dependencies {
  6. classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.2.RELEASE")
  7. }
  8. }
  9. apply plugin: 'java'
  10. apply plugin: 'org.springframework.boot'
  11. repositories {
  12. mavenCentral()
  13. }
  14. dependencies {
  15. testCompile group: 'junit', name: 'junit', version: '4.11'
  16. compile "org.springframework.boot:spring-boot-starter-web",
  17. 'ch.qos.logback:logback-core:1.1.3'
  18. }
  19. jar {
  20. baseName = 'spring-boot-app-web'
  21. version = '0.1.0'
  22. from configurations.compile.collect {
  23. it.isDirectory() ? it : zipTree(it)
  24. }
  25. exclude('org/slf4j/**')
  26. }



2. 在IDEA运行


在IDEA中可以直接运行SampleController这个类。



3. 打包直接运行


可以打成一个JAR包,直接运行,而不需要为的web容器。


打包:

$ ./gradlew clean build



运行:

$ java -jar build/libs/spring-boot-app-web-0.1.0.jar

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注