@xtccc
2016-12-21T00:58:56.000000Z
字数 2188
阅读 2035
Spring
Boot
目录:
SampleController.java
package cn.gridx.springboot.web;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.atomic.AtomicLong;
@SpringBootApplication
@RestController
public class SampleController {
Logger logger = LoggerFactory.getLogger(this.getClass());
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping(method = RequestMethod.GET, path = "/home")
public String home() throws InterruptedException {
logger.info("[home] 收到请求");
Thread.sleep(10*1000);
logger.info("[home] 返回响应");
return "Hello World!";
}
@RequestMapping(method = RequestMethod.GET, path = "/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name)
throws InterruptedException {
logger.info("[greeting] 收到请求");
Thread.sleep(10*1000);
logger.info("[greeting] 返回响应");
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleController.class, args);
}
}
Greeting.java
package cn.gridx.springboot.web;
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;
}
}
build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.2.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.11'
compile "org.springframework.boot:spring-boot-starter-web",
'ch.qos.logback:logback-core:1.1.3'
}
jar {
baseName = 'spring-boot-app-web'
version = '0.1.0'
from configurations.compile.collect {
it.isDirectory() ? it : zipTree(it)
}
exclude('org/slf4j/**')
}
在IDEA中可以直接运行SampleController这个类。
可以打成一个JAR包,直接运行,而不需要为的web容器。
打包:
$ ./gradlew clean build
运行:
$ java -jar build/libs/spring-boot-app-web-0.1.0.jar