本例使用 maven 作为项目管理工具
新建 pom.xml 文件,添加 spring-boot-starter-web 依赖:
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-web</artifactId> 4 <version>1.5.9.RELEASE</version> 5 </dependency>
pom.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4 <modelVersion>4.0.0</modelVersion> 5 6 <groupId>com.wangke</groupId> 7 <artifactId>spring-boot-helloworld</artifactId> 8 <version>1.0</version> 9 10 <parent> 11 <groupId>org.springframework.boot</groupId> 12 <artifactId>spring-boot-starter-parent</artifactId> 13 <version>1.5.9.RELEASE</version> 14 </parent> 15 16 <dependencies> 17 <dependency> 18 <groupId>org.springframework.boot</groupId> 19 <artifactId>spring-boot-starter-web</artifactId> 20 </dependency> 21 </dependencies> 22 23 <properties> 24 <java.version>1.8</java.version> 25 </properties> 26 27 <build> 28 <plugins> 29 <plugin> 30 <groupId>org.springframework.boot</groupId> 31 <artifactId>spring-boot-maven-plugin</artifactId> 32 </plugin> 33 </plugins> 34 </build> 35 36 </project>
创建一个控制器
1 package com.wangke.helloworld; 2 3 import org.springframework.web.bind.annotation.RestController; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 6 @RestController 7 public class HelloController { 8 9 @RequestMapping("/") 10 public String index() { 11 return "Hello World!"; 12 } 13 }
创建 Application 类
1 package com.wangke.helloworld; 2 3 import org.springframework.boot.SpringApplication; 4 import org.springframework.boot.autoconfigure.SpringBootApplication; 5 6 @SpringBootApplication 7 public class Application { 8 9 public static void main(String[] args) { 10 SpringApplication.run(Application.class, args); 11 } 12 }
项目结构
运行程序
mvn clean package && java -jar target/spring-boot-helloworld-1.0.jar
或者
mvn spring-boot:run