11

我正在使用 Spring Java 配置来创建我的 bean。但是这个 bean 对 2 个应用程序是通用的。两者都有一个属性文件 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

If you're using YAML properties, this can be achieved using a custom 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());
        }
    }
}

Usage:

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