classpath wildcard in @PropertySource

2019-01-23 17:05发布

I am using Spring Java config to create my bean. But this bean is common to 2 applications. Both have one property file abc.properties but with different classpath locations. When i put explicit classpath like

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

then it works but when i try to use wildcard like

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

then it doesn't work. I try many combinations of wildcard but it still not working. Is wildcard works in @ProeprtySource Is there any other way to read to property in classed marked with @Configurations.

2条回答
别忘想泡老子
2楼-- · 2019-01-23 17:33

Addidtionally to dmay workaround:

Since Spring 3.1 PropertySourcesPlaceholderConfigurer should be used preferentially over PropertyPlaceholderConfigurer and the bean should be static.

@Configuration
public class PropertiesConfig {

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

}
查看更多
叛逆
3楼-- · 2019-01-23 17:55

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

workaround: try

@Configuration
public class Test {

    @Bean
    public PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer()
            throws IOException {
        PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
        ppc.setLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/**/abc.properties"));
        return ppc;
    }
查看更多
登录 后发表回答