首页 > 解决方案 > 在 Spring Boot 中加速 YAML 文件处理

问题描述

我正在尝试使用 Spring Boot 中的@PropertySource注释读取 YAML 属性文件。
configuration.yaml文件有大约7.5K行数据,格式如下:

# Configuration for privilege management
---
role-configuration:
  roles:
    - name: Agent
      groups:
        -name: privilege-group
group-configuration:
  groups:
    - name: privilege-group
privilege-configuration:
  privileges:
    - name: admin-dashboard-view
      description: View Admin dashboard
      groups:
        - name: privilege-group
    - name: admin-dashboard-edit
      description: Edit Admin dashboard
      groups:
        - name: privilege-group
     ....
     ...
     ..

配置 beanYAML 特定的 PropertySourceFactory已通过以下链接实现

PrivilegeProvider.java

@Configuration
@ConfigurationProperties(prefix = "privilege-configuration")
@PropertySource(value = "classpath:security/configuration.yaml", factory = YamlPropertySourceFactory.class)
@Data # lombok annotation for generating getter/setter and other helper functions
public class PrivilegeProvider {
    private List<Privilege> privileges;
}

YamlPropertySourceFactory.java

public class YamlPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(encodedResource.getResource());

        Properties properties = factory.getObject();

        return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);
    }
}

所有数据都从 YAML 文件成功加载,但加载大约需要 5-7 分钟,考虑到文件大小,这是相当多的时间

这可以优化吗?还是有其他方法可以实现相同的?

标签: spring-bootyamlspring-bean

解决方案


推荐阅读