如何在 Spring 应用程序外部解析 Spring 格式的 application.properties 文件(例如在 gradle 构建脚本中)?

2024-03-03

我有一个包含 application.properties 文件的 Spring Boot 应用程序。 Spring 的属性处理让我可以做类似的事情

property1=my-value-${ENV_VARIABLE1}
property2=${property1}-extended

现在我需要 Gradle 构建脚本中此属性文件中的一些属性(数据库名称等)来生成 JOOQ 类。使用常规的 Java 属性解析器适用于简单的 .properties 文件,但不支持 Spring 的扩展,例如相互引用的属性文件和环境变量。

有没有办法像 Spring 那样解析属性文件?


我最近正在努力解决这个问题,并发现令人惊讶的是没有直接的方法来实现此功能。我什至开了一个issue https://github.com/spring-projects/spring-boot/issues/35852Spring Boot,但该功能被认为太复杂而难以实现。

尽管如此,我还是做了一个概念证明,支持多个 Spring 配置文件、优先级和变量插值以及 ENV 变量覆盖。它不是最干净的,也不完全反映 Spring Boot,但它应该可以满足大多数情况。这就是我将其集成到我的 build.gradle 文件中的方式:

import org.springframework.core.env.StandardEnvironment
import org.springframework.core.io.support.PathMatchingResourcePatternResolver
import org.springframework.core.io.support.ResourcePropertySource

sourceSets {
    main {
        java {
            srcDir ("src/main/java")
            srcDir ("build/generated/sources")
        }
    }
}

// Rest of build.gradle

// Extract properties as Spring Boot would
StandardEnvironment springBootEnvironment = new StandardEnvironment();
PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver()
String activeProfilesEnvVariable = "$System.env.spring_profiles_active"
String[] profiles = activeProfilesEnvVariable.split(",")
println "Active spring profiles: " + profiles
if (activeProfilesEnvVariable != "null" && profiles.length != 0) {
    for (final def profile in profiles) {
        for (final def resDir in sourceSets.main.getResources().srcDirs) {
            String searchPath = Paths.get("file:" + resDir.toString(), "application-" + profile + ".properties").toString()
            var resources = resourcePatternResolver.getResources(searchPath)
            for (final def res in resources) {
                springBootEnvironment.getPropertySources().addLast(new ResourcePropertySource(res))
            }
        }
    }
}
springBootEnvironment
        .getPropertySources()
        .addLast(
                new ResourcePropertySource(
                        resourcePatternResolver.getResource("file:src/main/resources/application.properties")
                )
        )

// Use a property
springBootEnvironment.getProperty("spring.datasource.username")

正如您所看到的,大部分代码都涉及属性文件的优先级和发现。如果您使用 yaml 属性文件,则可以使用YamlPropertySourceLoader。 你可以用以下命令运行 gradlespring_profiles_activeENV 变量设置为您想要的任何配置文件,就像您的 Spring Boot 应用程序一样

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Spring 应用程序外部解析 Spring 格式的 application.properties 文件(例如在 gradle 构建脚本中)? 的相关文章

随机推荐