利用Spring Boot可以快速搭建web项目,在IntelliJ(我用的版本是ideaIU-2017.3.4)下只需如下几步:
1.File->New->Project,出现如下界面,选择左侧的“Spring Initializr”:
2.点击“Next”,出现如下项目信息填写界面:
输入项目相关信息。
3.点击“Next”,出现Spring Boot插件选择界面,Spring Boot提供多个常用插件,可按实际需要选择,这里只选了web:
4.点击“Next”选择存储路径:
5.最后点击“Finish”即完成一个Spring Boot项目创建。项目结构如下:
运行“DemoApplication.java”就可以启动项目,快速便捷高效。
6.下面为了更好的演示,添加了一个Controller,结构图如下:
- 在application.properties文件中设置一个端口:
server.port = 8848
- TestContoller内容如下:
package com.example.demo.contoller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/hello")
public class TestController {
@RequestMapping(value = {""}, method = {RequestMethod.GET, RequestMethod.POST})
public String index() {
return "Hello World";
}
@GetMapping("/info")
public Map<String,String> getInfo() {
Map<String,String> map = new HashMap<>();
map.put("one","Hello!");
map.put("two","Hello!");
map.put("three","Hello!");
return map;
}
}
只需添加几个注解,设置路由,浏览器就能访问。
- 运行DemoApplication即可启动项目。Spring Boot默认WEB容器是Tomcat,如需用Jetty可在pom.xml中如下配置:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
版本继承于父项目“spring-boot-starter-parent”。
- 浏览器访问结果如下:
以上就是一个搭建Spring Boot 应用的过程。