使用spring-boot加载嵌套的yaml属性

时间:2015-11-04 14:20:34

标签: spring-boot yaml spring-properties

我在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文件的模式,请更正我的理解。

1 个答案:

答案 0 :(得分:1)

我发现今天早上到达这个问题时我犯了多个错误:

1)我的代码实际上没有加载任何自定义的名为yml的属性文件。相反,它正在拿起我在项目中也有的默认application.yml文件。

2)默认的application.yml文件的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

在理解了这两个问题之后,我能够从application.yml正确加载属性。

我为我的属性登陆的最终语法如下:

# Error Properties

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}