11

Spring Java config を使用して Bean を作成しています。ただし、この Bean は 2 つのアプリケーションに共通です。どちらにも 1 つのプロパティ ファイル abc.properties がありますが、クラスパスの場所が異なります。明示的なクラスパスを次のように配置すると

@PropertySource("classpath:/app1/abc.properties")

それは動作しますが、次のようなワイルドカードを使用しようとすると

@PropertySource("classpath:/**/abc.properties")

それは機能しません。ワイルドカードの多くの組み合わせを試しましたが、まだ機能しません。ワイルドカードは で機能し@ProeprtySource ますか? でマークされたクラスのプロパティを読み取る他の方法はありますか@Configurations?

4

3 に答える 3

19

@PropertySource API:Resource location wildcards (e.g. **/*.properties) are not permitted; each location must evaluate to exactly one .properties resource.

回避策: 試してください

@Configuration
public class Test {

    @Bean
    public PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer()
            throws IOException {
        PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
        ppc.setLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/**/abc.properties"));
        return ppc;
    }
于 2013-01-18T04:51:45.887 に答える
8

dmayの回避策に加えて:

Spring 3.1 以降、PropertySourcesPlaceholderConfigurer は PropertyPlaceholderConfigurer よりも優先的に使用する必要があり、Bean は静的である必要があります。

@Configuration
public class PropertiesConfig {

  @Bean
  public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
    PropertySourcesPlaceholderConfigurer propertyConfigurer = new PropertySourcesPlaceholderConfigurer();
    propertyConfigurer.setLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/**/abc.properties"));
    return propertyConfigurer;
  }

}
于 2013-09-01T16:19:54.423 に答える
0

YAML プロパティを使用している場合、これはカスタムを使用して実現できますPropertySourceFactory

public class YamlPropertySourceFactory implements PropertySourceFactory {

    private static final Logger logger = LoggerFactory.getLogger(YamlPropertySourceFactory.class);

    @Override
    @NonNull
    public PropertySource<?> createPropertySource(
            @Nullable String name,
            @NonNull EncodedResource encodedResource
    ) {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        String path = ((ClassPathResource) encodedResource.getResource()).getPath();
        String filename = encodedResource.getResource().getFilename();
        Properties properties;
        try {
            factory.setResources(
                    new PathMatchingResourcePatternResolver().getResources(path)
            );
            properties = Optional.ofNullable(factory.getObject()).orElseGet(Properties::new);
            return new PropertiesPropertySource(filename, properties);
        } catch (Exception e) {
            logger.error("Properties not configured correctly for {}", path, e);
            return new PropertiesPropertySource(filename, new Properties());
        }
    }
}

使用法:

@PropertySource(value = "classpath:**/props.yaml", factory = YamlPropertySourceFactory.class)
@SpringBootApplication
public class MyApplication {
    // ...
}
于 2021-02-17T06:43:27.510 に答える