SpringBoot的主要目的是简化配置文件,通过少量配置即可运行Java程序,其强大的自动配置功能帮助开发者轻松实现配置装配,通过引入SpringBoot的starter就能实现想要的功能,不需要额外的配置。
目前SpringBoot工程有三种搭建方式:
- 通过Spring Initializr创建
- 通过IDEA创建工程
- 手动创建工程
- 通过Spring Initializr创建
Spring团队提供一个非常方便的网页用于生成SpringBoot工程,打开浏览器进入 Spring Initializr:
工程生成参数列表:
Project: 工程类型(支持Maven和Gradle构建工具)
Language:
工程主要语言根据需要可选择Java、Kotlin、Groovy
SpringBoot:
SpringBoot版本
ProjectMatedata:
有Group和Artifact等配置
Dependencies:
工程依赖
参数设置完成后点击Generate下载工程,完成后使用IDEA导入工程,打开工程同步即可运行。
- 通过IDEA创建工程(笔者推荐)
笔者较为推荐这种方式,因为两个字 简单
较新的IDEA版本都内置创建SpringBoot工程插件,其创建原理也是使用的 Spring Initializr 来创建工程,创建流程下如:
打开IDEA开发工具
选择file -> new -> project菜单
在新的对话框中选择Spring Initializr
点击Next即可创建SpringBoot工程
最后main方法启动应用程序:
@SpringBootApplication
public class SbhelloApplication {
public static void main(String[] args) {
SpringApplication.run(SbhelloApplication.class, args);
}
}
3.手动创建工程
除了以上两种方式外,还可以通过手动创建的方式创建SpringBoot工程,通过IDEA创建一个空的Maven工程,然后指定SpringBoot的依赖就,基本流程如下:
打开IDEA开发工具
选择file -> new -> project菜单
在新的对话框中选择Mavenn
点击Next根据提示完成项目创建
工程创建完成后,打开pom.xml文件,设置pom.xml的parent配置:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.RELEASE</version>
</parent>
添加SpringBootMaven打包插件:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
添加main方法启动应用程序:
@SpringBootApplication
public class SbhelloApplication {
public static void main(String[] args) {
SpringApplication.run(SbhelloApplication.class, args);
}
}
完整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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zl</groupId>
<artifactId>sbhello</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>sbhello</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<!--将tomcat打包成可执行的jar-->
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
设置parent和插件后,就可以使用SpringBoot了。
欢迎关注"Java大讲堂" 微信公众号,获取更多内容