我正在构建一个库模块,作为构建 Spring 应用原生镜像的助手,例如添加 AOT bean 处理器和过滤器。我还需要在 AOT 期间设置一些 Spring 属性,然后激活一些在 AOT 期间要查找和注册的 bean 定义。
由于这是一个库,我无法控制正在构建的应用程序,因此我无法使用属性文件或环境变量来设置属性。我尝试过使用,EnvironmentPostProcessor
但看起来它在 AOT 处理期间没有被评估:
class EnableKubernetesEnvironemntPostProcessor implements EnvironmentPostProcessor {
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
environment.getPropertySources().addFirst(new MapPropertySource("enableKubernetes", Map.of(
"spring.main.cloud.platform", "kubernetes",
"spring.profiles.active", "kubernetes",
"management.server.port", "9000"
)));
}
}
如何在 AOT 处理期间以编程方式设置 Spring 属性?是否可以EnvironmentPostProcessor
在 AOT 期间触发?
具体来说,我需要设置spring.main.cloud.platform=kubernetes
,以便spring.profiles.active=kubernetes
AOT 选择符合这些属性条件的 bean,并且management.server.port
AOT 知道为 Actuator 使用不同的容器。
希望这个示例项目能够提供您所需要的内容。
云平台属性错误。应该是
spring.main.cloud-platform
。对于这种情况,最好在应用程序中手动尝试,然后转到EnvironmentPostProcessor
。那么您可能不希望在运行任何包含该库的应用程序时应用这些内容。为了缓解这种情况,您可以检查是否正在运行 AOT 处理,并仅在那里启用该行为。
以下是代码
我不能 100% 地确定为什么设置配置文件属性不能启用它,但
Environment
无论如何直接操作更好。