Spring Boot 优点
1.自动化配置,快速开发,轻松部署;
2.很好的融入docker,支持嵌入式的tomcat、jetty等容器
3.不需要打成war包,只需打成jar包直接运行即可
构建项目
1.通过官方Spring Initializr工具来生成,地址:http://start.spring.io/
2.点击Generate Project按钮,将代码下载到本地
3.解压,将该Maven项目导入到开发工具,导入后目录如下
工程结构分析
src/main/java:主程序入口HelloDemoApplication.java,可以通过直接运行该类来启动Spring Boot项目。
src/main/resources:配置目录,该目录下主要存放配置文件,如application.properties
src/test/:单元测试目录
Maven配置解析
打开pom.xml文件:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.lhb</groupId> <artifactId>helloDemo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>helloDemo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
其中groupId和artifactId对应生成项目时页面输入内容。打包形式为jar
父项目parent对应使用的Spring Boot版本,当前版本:2.0.3.RELEASE
项目依赖dependencies中:
spring-boot-starter-test:通用测试模块,包含Junit,Hamcrest,Mockito
spring-boot-starter-web:全栈web开发模块,包含嵌入式Tommat、Spring MVC
bulid部分,引入了Maven插件,可以方便启停应用,这样在开发时就不用每次去找主类或是打包jar来运行微服务,通过命令
mvn spring-boot : run 快速启动应用
RESTful API
新建一个包com.lhb.helloDemo.web,创建一个Controller类:
@RestController public class HelloController { @RequestMapping("/") public String index() { return "hello word"; } }
启动Spring Boot应用,在HelloDemoApplication.java中运行main方法
到浏览器中输入http://localhost:8080/,会看到如下页面:
这里需要注意的是:
在构建Spirng Boot应用时,需要注意目录文件结构,Application.java需要在Controller.java之上
否则在访问浏览器时会出现下列错误:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Jul 06 21:57:13 CST 2015
There was an unexpected error (type=Not Found, status=404).
No message available