我在我的 Java spring-boot 应用程序的 src/main/resources 中定义了以下 application-errors.yml 文件:
client:
badrequest: {code: 001, message: 'Malformed request', status: 400}
configuration: {code: 002, message: 'Invalid EC2 VPC configuration', status: 400}
server:
unexpected.error:
code: 004
message: 'Unexpected error occurred. Please try again'
status: 500
请注意,我尝试了两种不同的格式来指定属性。
我通过 @Configuration 注释类中的以下 Bean 加载该属性文件:
@Bean
public static YamlPropertiesFactoryBean getYamlProperties() {
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
yaml.setResources(new ClassPathResource("application-errors.yml"));
return yaml;
}
我看到属性是通过 Spring Environment 变量加载的,但不是我期望的模式。通过调试,我可以看到加载的属性文件的源包含以下值:
{client.badrequest=code:001 message:'Malformed request' status:400, client.configuration=code:002 message:'Invalid EC2 VPC configuration' status:400, server.unexpected.error=code:004 message:'Unexpected error occurred. Please try again' status:500}
看起来 yaml 文件被部分展平(只有两层深)。相反,我希望每个最终属性都可以自行展平。我期待的格式是这样的:
{client.badrequest.code=001, client.badrequest.message='Malformed request', client.badrequest.status=400, client.configuration.code=002, client.configuration.message='Invalid EC2 VPC configuration', client.configuration.status=400, server.unexpected.error.code=004, server.unexpected.error.message='Unexpected error occurred. Please try again', server.unexpected.error.status=500}
为了确保 Spring 在整个过程中使属性变平,我需要更改什么?如果我不理解 yaml 格式化模式或 Spring 正确展平 yaml 文件所遵循的模式,请纠正我的理解。