Ahead-of-Time(AOT)处理

当用户使用 Spring Boot 应用程序的提前(Ahead-of-Time,简称 AOT)处理时,常常会有一些疑问。 本节将解答这些问题。

条件评估

提前处理会对应用程序进行优化,并在构建时基于环境评估 @Conditional 注解。 Profiles 是通过条件实现的,因此也会受到影响。

如果你想在提前优化的应用程序中根据某个条件创建 bean,则必须在构建应用程序时设置好环境。 那些在构建时提前处理阶段创建的 bean,在运行应用程序时将始终被创建,无法关闭。 为此,你可以在构建应用程序时指定要使用的 profiles。

对于 Maven,可以通过配置 spring-boot-maven-plugin:process-aot 执行时的 profiles 参数来实现:

<profile>
    <id>native</id>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <executions>
                        <execution>
                            <id>process-aot</id>
                            <configuration>
                                <profiles>profile-a,profile-b</profiles>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</profile>

对于 Gradle,则需要配置 ProcessAot 任务:

tasks.withType(org.springframework.boot.gradle.tasks.aot.ProcessAot).configureEach {
    args('--spring.profiles.active=profile-a,profile-b')
}

在运行提前优化的应用程序时,仅更改不影响条件判断的配置属性的 profiles 将不受限制地支持。