Spring Bootでyamlプロファイルで使用されている概要


最近spring bootプロジェクトでyamlファイルをconf構成として使用し、真ん中にいくつかの穴を踏んでいます.ここで記録します.
1.カスタムyaml構成のロード
まず、私の新しい構成はapplication.yamlファイルではなく、個別にサブディレクトリの下に配置された構成です.最も重要な任務はspring bootが見つけてロードに成功する必要があります.ここでは、方法を使用する必要があります.
@Configuration
public class ConfManager {
     

    @Bean
    public static PropertySourcesPlaceholderConfigurer serviceConfig() {
     
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(new ClassPathResource("config1.yaml"),
                new ClassPathResource("subdir/config2.yaml"));
        configurer.setProperties(yaml.getObject());
        return configurer;
    }

}

複数のconfファイルがあれば,setResourcesメソッドにClassPathResourceの個数を増やすだけでよい.springでは@Bean修飾のPropertySourcesPlaceholderConfigurerしか定義できず、1つ注入した後に他のconfigurerをスキャンせず、複数注入するとbeanがnullの場合が発生することに注意してください.
2.@Value注入方式
Springが開始されると、@Componentで修飾されたclassに@Valueで修飾されたメンバーがいる場合、yaml構成で定義されたpathに従ってvalue注入が行われます.
a:
    b:
        c: value
@Component
class TestClass {
    @Value("${a.b.c}")
    private String c;
}

しかし、私が言いたいのはこれではなく、MapまたはListの構成を定義するときに、この方法を使用して注入に成功することはありません.次の例を見てください.
xxx-config:
  enable: false
  id: 1
  maps:
    shard1:
      - group01
      - group04
      - group07
    shard2:
      - group02
      - group05
      - group08
    shard3:
      - group03
      - group06
      - group09

@Value注記でmaps変数を注入
@Component
class TestClass {
     
    @Value("${xxx-config.maps}")
    Map<String, List<String>> maps;
}

次のように表示されます.
Could not resolve placeholder 'xxx-config.maps' in string value "${xxx-config.maps}"

このような間違いは,解決策は姿勢を変えることである.
@Data
@Component
@ConfigurationProperties(prefix = "xxx-config")
public class ShardConfig {
     

    boolean enable;

    int id;

    Map<String, List<String>> maps;

}

そして
@Component
class TestClass {
     
    @Resource
    private ShardConfig shardConfig;
}