1. SpringBoot 介绍
- SpringBoot 对 Spring 平台和第三方库进行了整合,可创建可以运行的、独立的、生产级的基于 Spring 的应用程序。(大多数 SpringBoot 应用程序只需要很少的 Spring 配置。)
SpringBoot 可以使用 java -jar 或更传统的 war 部署启动的 Java 应用程序进行创建,可以内嵌 Tomcat、Jetty、Undertow 容器,快速启动 web 程序。
1.1. 设计目标
为所有 Spring 开发提供更快且可通用的入门体验。
- 开箱即用,可以根据需求快速调整默认值。
- 提供大型项目(例如嵌入式服务器、运行状况检查和统一配置)通用的一系列非功能性功能。
- 绝对没有代码生成,也不需要 XML 配置。
1.2. SpringBoot 优势快速预览
2. 开发第一个 SpringBoot 项目
2.1. 依赖(pom.xml)
Maven 依赖管理 - spring-boot-dependencies 提供了 SB 支持的依赖,以及相关的版本定义。
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.1.3.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
引入 web 开发相关的依赖(无需再指定版本,由 spring-boot-dependencies 定义)
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
</dependencies>
2.2. 添加启动类
@SpringBootApplication
public class SpringbootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootDemoApplication.class, args);
}
}
2.3. 添加 Controller
@RestController
public class MyController {
@GetMapping("index")
public String index() {
return "hello world -maven";
}
}
3. 运行你的 SpringBoot 程序
- 通过 IDEA 运行 main 方法。
- maven 插件运行:
mvn spring-boot:run
,需要添加spring-boot-maven-plugin
到我们的 pom.xml 文件中。 - 创建可执行的 jar,需要添加
spring-boot-maven-plugin
到我们的 pom.xml 文件中。
- 注解默认扫描的包目录 basePackage 为启动类 Main 函数入口所在的包路径;
- 配置文件约定是 classpath 目录下的 application.yml 或者 application.properties;
- web 开发的静态文件放在 classpath,访问的顺序依次是:/META-INF/resources -> resources -> static -> public;
- web 开发中页面模板,约定放在 classpath 目录,/templates/ 目录下。