1 Star 0 Fork 1

YanWenkun/spring-boot-boilerplate-java

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

Spring Boot 样板项目(使用 Java 与 Maven)

本样板项目基于 Spring 官方的 Spring Initializr 生成的 Spring Boot 项目, 并添加一些实用的常见配置,便于在新项目启动时“简单修改即可复用”。

同时,本项目也将不断跟进上游最新版本,以便下游项目一站式更新。

本项目以容器或云引擎(例: 阿里云 SAE )为部署目标,简化传统的复杂配置,减少更新维护成本。

文件目录结构:

spring-boot-boilerplate-java
│  .editorconfig
│  .gitattributes
│  .gitignore
│  docker-compose.yml
│  Dockerfile
│  LICENSE
│  mvnw
│  mvnw.cmd
│  pom.xml
│  README.adoc
│
├─.mvn
│  └─wrapper
│          maven-wrapper.jar
│          maven-wrapper.properties
│          MavenWrapperDownloader.java
│
├─docs
│  │  Upgrade-Checklist.adoc
│  │
│  ├─logback
│  │      logback-spring.xml.example
│  │      logback-spring.xml.file.example
│  │      logback-spring.xml.jdbc.example
│  │      logback-spring.xml.sls.example
│  │      README.logback.adoc
│  │
│  └─maven
│          settings.xml
│          settings.xml.more-repos.example
│
└─src
    ├─main
    │  ├─java
    │  │  └─com
    │  │      └─example
    │  │          └─demo
    │  │                  DemoApplication.java
    │  │
    │  └─resources
    │      │  application-dev.yml
    │      │  application-prod.yml
    │      │  application.yml
    │      │
    │      ├─static
    │      │      .gitkeep
    │      │
    │      └─templates
    │              .gitkeep
    │
    └─test
        └─java
            └─com
                └─example
                    └─demo
                            DemoApplicationTests.java

项目信息

  • 构建工具:Maven

  • Java 版本:17

Spring Initializr 生成的 Spring Boot 项目相比,有如下变动:

  • git 行为配置

    • 一个通用的 .gitignore 文件(规定 git 自动忽略哪些文件)

    • 一个通用的 .gitattributes 文件(规定 git 对文本格式的处理)

    • 为空目录添加 .gitkeep 文件(0字节,仅占位,避免空目录被忽略)

  • 编辑器行为配置

    • .editorconfig 文件来规范字符编码、行尾、文件末尾、缩进格式等

  • Maven Wrapper 使用【阿里云】中国大陆的下载地址,改善下载速度

  • 包含一个基本的 README.adoc 自述文件,以便参考 AsciiDoc 语法

    • AsciiDoc 兼容 Markdown 语法,可在 adoc 中直接写 Markdown

  • 配置文件使用 YAML 格式( application.yml 取代 application.properties

  • 两个项目配置集

    • 两个 Maven Profile: dev, prod

    • 两个 Spring Profile: dev, prod

    • 启用 Maven Profile prod 会自动启用对应的 Spring Profile prod。而 dev 亦然

  • Docker 描述文件(Dockerfiledocker-compose.yml

    • 参照官方最佳实践,使用多段构建

  • docs 目录下附带若干帮助文件

    • 版本升级清单

    • Logback 日志配置样例

    • Maven 镜像源配置样例

运行指引

  • 如果你使用 Intellij IDEA / Spring Tool Suite,直接运行项目即可。

使用命令行运行

  • 如果你不想使用 IDE,可以用命令行的方式运行 Spring Boot 项目,你需要先在本地安装:

    • Git

    • JDK 17 或更高版本

执行命令:

git clone https://github.com/yanwenkun/spring-boot-boilerplate-java.git
cd spring-boot-boilerplate-java
./mvnw clean spring-boot:run

Ctrl + C 可终止运行。

使用 Docker Compose 运行

如果你安装有 Docker Desktop,直接运行以下命令,即可构建镜像并运行容器:

git clone https://github.com/yanwenkun/spring-boot-boilerplate-java.git
cd spring-boot-boilerplate-java
docker-compose up --build

Ctrl + C 可终止运行。

修改成你的项目

  1. 全局搜索 DemoApplication ,并替换为你的程序名称,比如 SampleApplication (建议保留 Application 后缀)

  2. 全局搜索 com.example.demo ,并替换为你的软件包名称,比如 fun.yanwenkun.sample

  3. 全局搜索 com.example ,并替换为你的组织名称,比如 fun.yanwenkun

  4. 修改 pom.xml 中的软件制品信息(GAV),并管理你的依赖项

  5. 修改代码文件对应的路径、文件名(可通过 IDE 的重构功能完成)

  6. 修改 docker-compose.yml 中的容器与镜像名称

配置集的使用

Table 1. 配置集与运行环境样板
启用配置集 运行环境 数据源 日志级别(业务) 日志级别(框架)

@Profile("dev")

开发环境 Development

运行时 H2 内存数据库

TRACE

INFO

@Profile("prod")

线上测试环境 Testing

测试数据库

DEBUG

INFO

预发环境 Staging

生产数据库

INFO

WARN

生产环境 Production

生产数据库

WARN

ERROR

在实际生产中,该表会更为复杂,但原则不变:使问题尽早暴露、尽早解决。
从脱离本地开发环境开始,所有代码与依赖项均应与生产环境一致,仅配置不同。

Profile 用法

  • Spring Profile 在 Java/Kotlin 代码中的用法:

    • 使用Spring注解: @Profile("dev")

    • 未标 @Profile 注解的代码段,均与配置集无关

  • Maven Profile 不关心 Java 代码中的注解,只关心编译资源(依赖项),pom.xml 中对此有举例

以配置集运行

  • 使用 IDE 可以直接切换配置集

  • 默认激活: dev

  • prod 运行:

./mvnw clean spring-boot:run -P prod
  • 如何修改默认配置集:

    • 修改 pom.xml 中的 activeByDefault 属性

    • 注意仅保持 1 个 activeByDefaulttrue

      • Maven 可以同时激活多个 Profile,但 Spring 只允许同时激活一个

  • Dockerfile 已配置为默认使用 prod

  • 编译服务如 Jenkins 应配置相关参数,代码仓库本身应面向开发者

日志的配置

  • 容器环境下,日志输出到 STDOUT(标准输出、命令行输出)即可,由容器管理日志的收集

  • 程序只需要配置日志输出等级,修改 application-{$profile}.yml 即可

  • 如需详细配置 Logback,请参考本项目中的 Spring Logback 日志配置参考

建议:

  • 编写代码时不要用 System.out.println(),而是使用 Slf4j 分等级记录日志

    • 可用等级(从低到高): TRACE DEBUG INFO WARN ERROR

    • Lombok 可以使用 @Slf4j 注解减少代码,但本项目没有引入该依赖

附录一:JDK 的选择

Oracle JDK 的收费背景

  • 在以往几乎完全免费的 Oracle JDK ,从2019年开始,只对开发、个人使用免费,用于生产环境需要付费

  • 在 2021 年 9 月发布的 Oracle JDK 17,又可以免费用于生产环境了,但只提供三年支持。三年之后要么升级大版本,要么付费买支持,要么停留在最后的免费版本(不安全)

  • 而完全免费的 Oracle OpenJDK 只更新最新 GA 大版本,每当新的大版本 GA,老版本即停止更新

    • Oracle 这么做是为了鼓励开发者跟进新版本,同时也扩大老版本的维护收费

  • 个人建议

    • 对于企业开发,“追新”是为了保持先进、与主流同步,“追最新”则容易踩坑、增加成本。正所谓“领先一步是先驱,领先两步是先烈” :-)

    • Java 的下一个长期支持版本(LTS)是 21,预计 2023 年 9 月推出,在其广泛可用(GA)之前,建议维持在 Java 17

使用其它提供方的 OpenJDK

考虑以下几点:

  • 开源

  • 有健壮支持

  • 完全免费

推荐如下:

  • Eclipse Temurin

    • 即原先的 AdoptOpenJDK + HotSpot

    • 来自 Java 社区重要成员支持的 OpenJDK

    • 涵盖大版本较广(8、11、16、17、18 …)

    • 老版本(< 16)提供 JRE

  • IBM Semeru

    • 即原先的 AdoptOpenJDK + OpenJ9

    • OpenJ9 是来自 IBM 的开源 JVM,为云环境、容器化优化,内存占用小,提供快速启动选项

    • 除了 JDK 之外,每个版本还提供 JRE

  • Alibaba Dragonwell

    • 阿里巴巴开源的 OpenJDK

    • 为 LTS 版本提供长期支持

    • 随阿里云的工具链分发

  • Amazon Corretto

    • 亚马逊开源的 OpenJDK

    • 为 LTS 版本提供长期支持

如果你感到选择困难,请使用 Eclipse Temurin ,它的兼容性最佳。

附录二:配置集的理解

  • Profile 直译即“档案”,此处理解为配置、配置集

  • 配置集包含:配置项 + 专有依赖 + 专有代码

  • 对于代码本身,为避免过度复杂,仅使用 2 个配置集:

    • 开发阶段专有代码: @Profile("dev")

    • 生产阶段专有代码: @Profile("prod")

Profile 与 Profile 的不同

  • 在本项目中有两种 Profile:

    1. Spring Profile

    2. Maven Profile

  • 两者的实际作用域不同

    • Spring Profile 关心代码与配置项

    • Maven Profile 关心编译与依赖项

  • 为了便于统一管理,本项目中 Spring Profile 和 Maven Profile 共用同一套名称,并通过配置上的绑定,对两者进行了关联

    • 比如,Maven 启用了 prod,Spring 也会启用 prod

    • 但反过来不会

  • 如果配置不当,这两种 Profile 可能会冲突

    • 同一时间只能有一个 Spring Profile 激活

    • 同一时间可以有多个 Maven Profile 激活(在本项目中不推荐这么做)

Profile 的命名

  • devprod 两个命名是 Java 世界中的常见习惯,简洁明了,本项目尊重该习惯

  • Profile 命名并无绝对标准,比如 Spring 官方文档 中就使用了 devstagingproduction 作为例子

  • 为了避免开发者误解“Profile”与“运行环境”之间的关系,本项目仅使用 devprod 这两个 Profile

    • dev 仅在开发环境有效,脱离开发环境即开始使用 prod,使潜在问题尽早暴露

实际上,在高度 CI/CD 化之后,开发者不需要过多关心运行环境,而是应该精简配置、写好配置样板,供运维在不同阶段灵活部署。

某种意义上,这两个 Profile 的含义可以理解为 DEBUGRELEASE,或者 localonline

概念上的简化

  • 开发(本地编码)、验证(各类测试)、生产(发布上线):

    1. 既是软件生命周期中的“阶段”

    2. 也是运维与服务治理中的“环境”

  • 分得过于详细,有过度设计之虞,概念越多越容易出错

  • 作为“偷懒”的做法,将阶段和环境合为一谈,主要目的在于减少心智负担

    • 但扩大开发规模的时候,还是要注意概念上的区分

更多信息

  • Maven 与 Spring 共用 Profile name 并不是高枕无忧的设计

    • 主要看 Profile 是否与自动化流水线能够流畅配合

  • 如果不需要 Maven 根据环境/阶段管理不同的依赖,可以在 pom.xml 中删除 Profiles 相关定义

    • 如果去掉了 Maven Profiles,可以使用环境变量,使 Spring Boot 程序运行时直接调用不同配置集:

export SPRING_PROFILES_ACTIVE=prod

附录三

版本升级清单

见: 版本升级清单

为什么不默认使用 Lombok

从工程管理的角度出发,Java 项目保持其代码风格的延续是很重要的。而 Lombok 的侵入性,对老项目而言是需要权衡的,请根据团队的意见做出选择。

对于没有历史负担的新项目,可以考虑 Kotlin

使用 Maven 构建 Docker 镜像

在不配置 Maven 插件(即不改动 pom.xml)的前提下,最简单的方法是使用命令行调用 Google Jib:

  • 用法1:构建镜像

./mvnw com.google.cloud.tools:jib-maven-plugin:dockerBuild -Dimage="example/demo:dev"
  • 用法2:构建镜像并推送至仓库(Docker Registry)

./mvnw com.google.cloud.tools:jib-maven-plugin:build -Dimage="example/demo:dev"

注意修改镜像名称与标签 example/demo:dev
推送至仓库前需要先登录(docker login)。

配置 Maven 使用镜像源

在中国大陆访问 Maven 官方源一般会很慢,建议使用镜像源。

  • 不推荐直接在 pom.xml 中配置仓库来源

    • 因为初次构建时还是要从官方源下载包,依然很慢

    • 不利于 CI 的管理

如何配置本地 Maven 使用镜像源:

将【 settings.xml 】复制到【 用户主目录/.m2/ 】下。 或执行命令:

mkdir ~/.m2/
cp docs/maven/settings.xml ~/.m2/

如需 Maven Central 以外的仓库源,请参考【 settings.xml.more-repos.example 】。

许可

本项目使用与 Spring Boot 一致的 Apache License 2.0 许可。

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

Spring Boot 样板项目(使用 Java 与 Maven) 展开 收起
README
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yanwenkun/spring-boot-boilerplate-java.git
git@gitee.com:yanwenkun/spring-boot-boilerplate-java.git
yanwenkun
spring-boot-boilerplate-java
spring-boot-boilerplate-java
master

搜索帮助