无法从 Spring 启动应用程序中的自定义 yml 文件加载配置



我正在从 application.yml 加载我的 Spring 启动服务中的自定义配置。

我按豆类注释如下,

@Component
@ConfigurationProperties("app")
public class ContinentConfig {
private Map<String, List<Country>> continents = new HashMap<String, List<Country>>();
//get/set/tostring methods
}

我的自定义类国家/地区包括 2 个字段,

public class Country {
String name;
String capital;
//get/set/tostring methods
}

在应用程序.yml中,我有如下,

app:
continents: 
Europe: 
- name: France
capital: Paris
Asia: 
- name: China
capital: Beijing       

通过上述设置,我能够从application.yml加载配置。

我现在想将配置提取到同一个src/main/resources文件夹中的单独continentconfig.yml。因此,我将自定义配置移动到 continentconfig.yml,在 application.yml 中保留了其他属性,如server.port

continentconfig.yml的内容与我之前在application.yml中的内容相同。

我还在 ContinentConfig 类中添加了以下注释,

@Component
@ConfigurationProperties("app")
@EnableConfigurationProperties
@PropertySource(value="classpath:continentconfig.yml")
public class ContinentConfig {
}

在此更改之后,我看到配置没有从continentconfig.yml加载到ContinentConfigbean。

有人可以帮助解决问题吗?

简短的回答你不能这样做,你应该使用属性文件。

24.6.4 YAML 缺点

无法通过@PropertySource批注加载 YAML 文件。所以在 在您需要以这种方式加载值的情况下,您需要使用 属性文件。

您可以创建初始值设定项并使用YamlPropertySourceLoader

我相信通过外部化,你的意思是使用属性文件从 github/或其他此类托管存储库中配置的文件加载配置? 你可以通过使用bootstrap.yml来做到这一点。这会从外部文件加载所有配置,并允许预配使用本地应用程序覆盖它们。

春天: 应用: 名字: 云: 配置 : 乌里 :

还要确保你的pom中有春天的云来解决这个问题,以防万一

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter</artifactId>
</dependency>

以防万一您的本地 yml 属性文件未加载到您的类路径中,然后添加以下内容

<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.yml</include>
<include>**/*.jks</include>
</includes>
</resource>
</resources>

注意:最好使用 YamlPropertySourceLoader 将配置文件加载到类路径中,在此基础上,您可以使用上述配置

最新更新