阿里云发布 Spring Boot 新脚手架,真香
The following article is from 阿里巴巴中间件 Author 良名
来自公众号:阿里巴巴云原生
作者:良名,阿里巴巴技术专家
为每个组件提供了单独的 DemoCode 和对应的配置样例(本次已发布);
工程内置说明,减少用户查找文档的困难(部分实现);
开发者只需要做减法,而非加法的使用方式(部分实现);
提供多组件集成的解决方案(开发中);
定期跟进 start.spring.io 的更新,方便大家使用到 spring 的最新功能。
使用篇
1. 基本用法
依赖引入
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.spring.initializr</groupId>
<artifactId>initializr-bom</artifactId>
<version>0.9.0.BUILD-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependency>
<groupId>io.spring.initializr</groupId>
<artifactId>initializr-generator-spring</artifactId>
</dependency>
<dependency>
<groupId>io.spring.initializr</groupId>
<artifactId>initializr-version-resolver</artifactId>
</dependency>
<dependency>
<groupId>io.spring.initializr</groupId>
<artifactId>initializr-web</artifactId>
</dependency>
initializr-actuator: 监控诊断的附加信息,这个暂时忽略; initializr-bom: 便于外部使用的bom依赖; initializr-docs: 使用文档; initializr-generator: 核心工程生成库; initializr-generator-spring: 用于生成典型的spring boot工程; initializr-generator-test: 测试框架; initializr-metadata: 项目各个方面的元数据基础结构; initializr-service-sample: 基本使用案例; initializr-version-resolver:版本号解析能力; initializr-web: 提供给三方客户端使用的web入口。
基本配置
完成了框架引入,就需要做一些基础配置了
支持哪些语言:Java、groovy、Kotlin
支持哪些版本:1.8、11、13
支持哪些打包方式:jar、war
initializr:
packagings:
- name: Jar
id: jar
default: true
- name: War
id: war
default: false
javaVersions:
- id: 13
default: false
- id: 11
default: false
- id: 1.8
name: 8
default: true
languages:
- name: Java
id: java
default: true
- name: Kotlin
id: kotlin
default: false
- name: Groovy
id: groovy
default: false
initializr:
types:
- name: Maven Project
id: maven-project
description: Generate a Maven based project archive.
tags:
build: maven
format: project
default: true
action: /starter.zip
- name: Maven POM
id: maven-build
description: Generate a Maven pom.xml.
tags:
build: maven
format: build
default: false
action: /pom.xml
- name: Gradle Project
id: gradle-project
description: Generate a Gradle based project archive.
tags:
build: gradle
format: project
default: false
action: /starter.zip
- name: Gradle Config
id: gradle-build
description: Generate a Gradle build file.
tags:
build: gradle
format: build
default: false
action: /build.gradle
/pom.xml 生成一个 Maven 的 pom.xml 配置文件 /build.gradle 生成 Gradle 的配置文件 /starter.zip 生成 zip 方式压缩的工程文件 /starter.tgz 生成以 tgz 方式压缩的工程文件
配置基本依赖
initializr:
dependencies:
- name: Web
content:
- name: Web
id: web
description: Full-stack web development with Tomcat and Spring MVC
- name: Developer Tools
content:
- name: Spring Boot DevTools
id: devtools
groupId: org.springframework.boot
artifactId: spring-boot-devtools
description: Provides fast application restarts, LiveReload, and configurations for enhanced development experience.
- name: Lombok
id: lombok
groupId: org.projectlombok
artifactId: lombok
description: Java annotation library which helps to reduce boilerplate code.
id:组件的唯一标识符 groupId & artifactId:组件的坐标 name:显示名称 description:描述信息,主要用于展示用途 version:组件版本
关于 groupId & artifactId:如果设置了坐标,生成的项目里会使用这里的坐标定位组件;但是如果没有设置坐标,框架会认为这是一个标准的 spring-boot 组件,自动添加 spring-boot-starter-{id} 作为生成的依赖坐标。
关于 version:如果直接在组件上设置版本信息,框架会直接使用这个值作为组件依赖的版本;但是很多时候,组件的版本会受到 spring-boot 版本的影响,此时就需要对版本做特殊的定义 & 管理。
配置依赖版本管理
M:里程碑版本 RC:发布候选版本 RELEASE:发布版本 BUILD-SNAPSHOT:为开发构建的快照版本
直接定义在组件(或 Bom )上
initializr:
dependencies:
- name: Stuff
content:
- name: Foo
id: foo
...
compatibilityRange: 1.2.0.M1
- name: Bar
id: bar
...
compatibilityRange: "[1.5.0.RC1,2.0.0.M1)"
定义在组件的 mappgin 属性下
initializr:
dependencies:
- name: Stuff
content:
- name: Foo
id: foo
groupId: org.acme.foo
artifactId: foo-spring-boot-starter
compatibilityRange: 1.3.0.RELEASE
mappings:
- compatibilityRange: "[1.3.0.RELEASE,1.3.x.RELEASE]"
artifactId: foo-starter
- compatibilityRange: "1.4.0.RELEASE"
使用 Bom 管理版本:有时候,需要使用 Bom 的方式管理组件版本;此时不需要对组件单独设置版本号。
initializr:
env:
boms:
my-api-bom:
groupId: org.acme
artifactId: my-api-dependencies
version: 1.0.0.RELEASE
repositories: my-api-repo-1
initializr:
dependencies:
- name: Other
content:
- name: My API
id : my-api
groupId: org.acme
artifactId: my-api
bom: my-api-bom
2. 高级定制
启用缓存
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
</dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
为不同的组件增加独立配置:还记得原理篇中提到的 spring.factories 吗?对,我们要增加自己的配置项,就需要在这里增加针对不同组件样例代码的扩展入口。
io.spring.initializr.generator.project.ProjectGenerationConfiguration=\
com.alibaba.alicloud.initializr.extension.dependency.springboot.SpringCloudProjectGenerationConfiguration
@ProjectGenerationConfiguration
public class SpringCloudAlibabaProjectGenerationConfiguration {
private final InitializrMetadata metadata;
private final ProjectDescription description;
private final IndentingWriterFactory indentingWriterFactory;
private final TemplateRenderer templateRenderer;
public SpringCloudAlibabaProjectGenerationConfiguration(InitializrMetadata metadata,
ProjectDescription description,
IndentingWriterFactory indentingWriterFactory,
TemplateRenderer templateRenderer) {
this.metadata = metadata;
this.description = description;
this.indentingWriterFactory = indentingWriterFactory;
this.templateRenderer = templateRenderer;
}
@Bean
@ConditionalOnRequestedDependency("sca-oss")
public OSSDemoCodeContributor ossContributor() {
return new OSSDemoCodeContributor(description, templateRenderer);
}
......
}
生成具体的 Demo 代码:继续以 OSSDemoCodeContributor 为例,它是一个 ProjectContributor ,会在项目文件空间创建完成了调用。我们需要为这个 Contributor 在实例化时增加生成过程中需要的元数据信息,例如 ProjectDescription 。
private void writeCodeFile(TemplateRenderer templateRenderer, Language langeuage,
Map<String, Object> params, Path path, String temp) throws IOException {
......
Path pkgPath = 生成包路径
Path filePath = 成成代码文件路径
// 渲染模板
String code = templateRenderer.render(temp, params);
// demo 文件写入
Files.createDirectories(pkgPath);
Files.write(filePath, code.getBytes("UTF-8"));
}
原理篇
启动阶段:启动应用,加载配置,扩展信息初始化; 生成阶段:一个项目生成,从收到请求,到返回内容的完整流程。
1. 启动阶段
initializr-generator/src/main/resources/META-INF/spring.factories
initializr-generator-spring/src/main/resources/META-INF/spring.factories
initializr-web/src/main/resources/META-INF/spring.factories
initializr-actuator/src/main/resources/META-INF/spring.factories
start-site/src/main/resources/META-INF/spring.factories
@Configuration
@EnableConfigurationProperties(InitializrProperties.class)
public class InitializrAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public ProjectDirectoryFactory projectDirectoryFactory()
@Bean
@ConditionalOnMissingBean
public IndentingWriterFactory indentingWriterFactory()
@Bean
@ConditionalOnMissingBean(TemplateRenderer.class)
public MustacheTemplateRenderer templateRenderer(Environment environment, ObjectProvider<CacheManager> cacheManager)
@Bean
@ConditionalOnMissingBean
public InitializrMetadataUpdateStrategy initializrMetadataUpdateStrategy(RestTemplateBuilder restTemplateBuilder,
ObjectMapper objectMapper)
@Bean
@ConditionalOnMissingBean(InitializrMetadataProvider.class)
public InitializrMetadataProvider initializrMetadataProvider(InitializrProperties properties,
InitializrMetadataUpdateStrategy initializrMetadataUpdateStrategy)
@Bean
@ConditionalOnMissingBean
public DependencyMetadataProvider dependencyMetadataProvider()
@Configuration
@ConditionalOnWebApplication
static class InitializrWebConfiguration {
@Bean
InitializrWebConfig initializrWebConfig()
@Bean
@ConditionalOnMissingBean
ProjectGenerationController<ProjectRequest> projectGenerationController(
InitializrMetadataProvider metadataProvider, ApplicationContext applicationContext)
@Bean
@ConditionalOnMissingBean
ProjectMetadataController projectMetadataController(InitializrMetadataProvider metadataProvider,
DependencyMetadataProvider dependencyMetadataProvider)
@Bean
@ConditionalOnMissingBean
CommandLineMetadataController commandLineMetadataController(InitializrMetadataProvider metadataProvider,
TemplateRenderer templateRenderer)
@Bean
@ConditionalOnMissingBean
SpringCliDistributionController cliDistributionController(InitializrMetadataProvider metadataProvider)
}
}
初始化元数据 Provider 创建模板引擎 创建目录、缩进工厂 初始化 web 配置 创建 spring mvc 的 web 入口 各种 ProjectGenerationController
2. 生成阶段
蓝色的类,是在应用启动阶段就完成了创建和数据填充;其生命周期和整个应用一致; 黄色的类,会在具体的项目构建过程中生成;其生命周期在一次项目生成流程之内结束。
主干流程
扩展流程
MavenBuildProjectContributor:写入 maven 项目 pom.xml 文件; WebFoldersContributor:创建 web 项目的资源文件夹; ApplicationPropertiesContributor:写入 application.properties 文件; MainSourceCodeProjectContributor:写入应用入口类 xxxApplication.java 文件; HelpDocumentProjectContributor:写入帮助文档 HELP.md 文件。
MainApplicationTypeCustomizer:自定义 MainApplication 类; MainCompilationUnitCustomizer:自定义 MainApplication 编译单元; MainSourceCodeCustomizer:自定义 MainApplication 源码; BuildCustomizer:自定义项目构建工具的配置内容; GitIgnoreCustomizer:自定义项目的 .gitignore 文件; HelpDocumentCustomizer:自定义项目的帮助文档; InitializrMetadataCustomizer:自定义项目初始化配置元数据;这个 Customizer 比较特殊,框架会在首次加载元数据配置时调用; ProjectDescriptionCustomizer:自定义 ProjectDescription ;即在生成项目文件之前,允许调整项目描述信息; ServletInitializerCustomizer:自定义 web 应用在类上的配置内容; TestApplicationTypeCustomizer:自定义测试 Application 类; TestSourceCodeCustomizer:自定义测试 Application 类的源码。
参考资料
1. 相关链接
initializr 说明文档
spring-initializr 项目地址
start.spring.io 项目地址
2. spring.factories 明细
initializr-generator/src/main/resources/META-INF/spring.factoriesio.spring.initializr.generator.buildsystem.BuildSystemFactory=\
io.spring.initializr.generator.buildsystem.gradle.GradleBuildSystemFactory,\
io.spring.initializr.generator.buildsystem.maven.MavenBuildSystemFactory
io.spring.initializr.generator.language.LanguageFactory=\
io.spring.initializr.generator.language.groovy.GroovyLanguageFactory,\
io.spring.initializr.generator.language.java.JavaLanguageFactory,\
io.spring.initializr.generator.language.kotlin.KotlinLanguageFactory
io.spring.initializr.generator.packaging.PackagingFactory=\
io.spring.initializr.generator.packaging.jar.JarPackagingFactory,\
io.spring.initializr.generator.packaging.war.WarPackagingFactory
io.spring.initializr.generator.project.ProjectGenerationConfiguration=\
io.spring.initializr.generator.spring.build.BuildProjectGenerationConfiguration,\
io.spring.initializr.generator.spring.build.gradle.GradleProjectGenerationConfiguration,\
io.spring.initializr.generator.spring.build.maven.MavenProjectGenerationConfiguration,\
io.spring.initializr.generator.spring.code.SourceCodeProjectGenerationConfiguration,\
io.spring.initializr.generator.spring.code.groovy.GroovyProjectGenerationConfiguration,\
io.spring.initializr.generator.spring.code.java.JavaProjectGenerationConfiguration,\
io.spring.initializr.generator.spring.code.kotlin.KotlinProjectGenerationConfiguration,\
io.spring.initializr.generator.spring.configuration.ApplicationConfigurationProjectGenerationConfiguration,\
io.spring.initializr.generator.spring.documentation.HelpDocumentProjectGenerationConfiguration,\
io.spring.initializr.generator.spring.scm.git.GitProjectGenerationConfiguration
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
io.spring.initializr.web.autoconfigure.InitializrAutoConfiguration
org.springframework.boot.env.EnvironmentPostProcessor=\
io.spring.initializr.web.autoconfigure.CloudfoundryEnvironmentPostProcessor
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
io.spring.initializr.actuate.autoconfigure.InitializrActuatorEndpointsAutoConfiguration,\
io.spring.initializr.actuate.autoconfigure.InitializrStatsAutoConfiguration
io.spring.initializr.generator.project.ProjectGenerationConfiguration=\
io.spring.start.site.extension.build.gradle.GradleProjectGenerationConfiguration,\
io.spring.start.site.extension.build.maven.MavenProjectGenerationConfiguration,\
io.spring.start.site.extension.dependency.DependencyProjectGenerationConfiguration,\
io.spring.start.site.extension.dependency.springamqp.SpringAmqpProjectGenerationConfiguration,\
io.spring.start.site.extension.dependency.springboot.SpringBootProjectGenerationConfiguration,\
io.spring.start.site.extension.dependency.springcloud.SpringCloudProjectGenerationConfiguration,\
io.spring.start.site.extension.dependency.springdata.SpringDataProjectGenerationConfiguration,\
io.spring.start.site.extension.dependency.springintegration.SpringIntegrationProjectGenerationConfiguration,\
io.spring.start.site.extension.dependency.springrestdocs.SpringRestDocsProjectGenerationConfiguration,\
io.spring.start.site.extension.description.DescriptionProjectGenerationConfiguration,\
io.spring.start.site.extension.code.kotin.KotlinProjectGenerationConfiguration