代码地址:https://github.com/mengyan183/spring-family/tree/main/spring-hellowold
对于spring使用学习,主要还是基于springboot 脚手架,其提供了快速开发特性,对于我们现在所说的spring并不仅代表spring framework,而是代表了整个spring家族
https://start.spring.io/
可以通过当前地址来快速搭建一个springboot工程
可以看到一下目录结构
对于pom.xml文件重点解读
springboot之所以作为一个快速开发脚手架原因就在于其提供了丰富的starter
Q:如果判断当前工程是否为springboot工程?
A: 引入了spring-boot相关依赖;对此官方提供了两种依赖方式
1:直接将spring-boot-starter-parent作为 parent引入, 方式如下
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.1</version> <!--表示当前依赖的springboot 版本号--> <relativePath/> <!-- lookup parent from repository --> </parent>
2:通过 dependencyManagement 标签引入 spring-boot-dependencies,一般建议采用当前方式引入,这样就可以自定义当前项目的parent
<dependencyManagement> <dependencies> <!--当前方式表示将spring-boot-dependencies作为pom引入--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.4.1</version> <type>pom</type> <!--表示引入的类型,由于默认为jar,因此需要显式声明--> <scope>import</scope> <!--表示当前作用域只是将其引入--> </dependency> </dependencies> </dependencyManagement>
Q:关于spring-boot-maven-plugin配置?
A:当我们使用maven作为包管理工具,就需要引入maven相关插件
对于上述第一个问题,实际也会影响到 当前插件的配置;
1:当引入spring-boot-starter-parent时,通过查看其pom文件可以看到存在一下内容
<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <id>repackage</id> <goals> <goal>repackage</goal> </goals> </execution> </executions> <configuration> <mainClass>${start-class}</mainClass> </configuration> </plugin>
说明当我们自定义引入以下插件时,实际就默认使用了parent中的相关配置,无需再自己配置
<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin>
2:当引入的为spring-boot-dependencies pom文件时, 就需要参考 starter-parent 中的maven-plugin配置进行自定义显式声明配置
<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.4.1</version> <executions> <execution> <goals> <!--表示当前plugin在执行时使用的是 repackage命令--> <goal>repackage</goal> </goals> </execution> </executions> </plugin>
Q:在使用spring-boot-maven-plugin时如何指定类似 编译版本和编码格式?
A:
<properties> <java.version>1.8</java.version> <!--设置当前maven source jdk编译版本--> <maven.compiler.source>1.8</maven.compiler.source> <!--设置当前maven target jdk编译版本--> <maven.compiler.target>1.8</maven.compiler.target> <!--设置当前项目构建编码格式--> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties>
Q:如果当前项目为一个web项目,需要配置什么?
A:首先需要引入 spring-boot-starter-web 依赖,在当前依赖中默认引入了 spring-boot-starter-tomcat ,说明默认使用tomcat作为web容器;也可以通过自定义的方式引入其他web容器;
对于当前web项目,默认启动端口为 8080, 可以通过修改 application.properties 中的 server.port = 端口号 来实现自定义端口
Q:服务健康检查
A:对于web服务,需要通过健康检查来判断当前web服务状态
首先需要引入 spring-boot-starter-actuator, 通过 当前项目根访问路径/actuator/health 请求来判断服务启动状态,并提供了其他的api请求检查方式
原文:https://www.cnblogs.com/xingguoblog/p/14130489.html