spring PropertySource properties 文件配置

  • bean定义引入配置文件

PropertySource注解不支持YAML files.所以只能使用properties文件

@Configuration
@PropertySource(value = {"classpath:permission/resource-type.properties"})
@ConfigurationProperties("permission")
@Data
public class DataPermissionType {
    private String model;
    private List<Param> param;
    private Param tenant;
    private Map<String,String> map;
    private int num;

    @Data
    public static class Param {
        private String name;
        private List<String> value;

        public Param() {
        }

        public Param(String name, List<String> value) {
            this.name = name;
            this.value = value;
        }
    }
}
  • 配置文件配置
permission.param[0].name=TENANT
permission.param[0].value[0]=tenant
permission.param[1].name=MODULE
permission.param[1].value[0]=oneservice
permission.tenant.name=TENANT
permission.tenant.value[0]=tenant
permission.map.key1=value1
permission.map.key2=value2
permission.num=1
permission.model=TENANT/MODULE/PROJECT/DATA
  • 输出结果
  DataPermissionType(model=TENANT/MODULE/PROJECT/DATA, param=[DataPermissionType.Param(name=TENANT, value=[tenant]), DataPermissionType.Param(name=MODULE, value=[oneservice])], tenant=DataPermissionType.Param(name=TENANT, value=[tenant]), map={key2=value2, key1=value1}, num=1)

  • @PropertySource支持yaml格式文件
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);
    }
}

参考资料

posted @ 2021-11-16 17:20  橙木鱼  阅读(266)  评论(0编辑  收藏  举报