@PropertySource中的类路径通配符



我使用Spring Java config来创建我的bean。但是这个bean对于2个应用程序是通用的。两者都有一个属性文件abc。属性,但具有不同的类路径位置。当我使用显式的类路径如

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

就可以了但是当我尝试使用通配符,比如

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

则不起作用。我尝试了许多通配符的组合,但它仍然不起作用。通配符在@ProeprtySource工作吗

是否有其他方法读取标记为@Configurations的class中的属性?

@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;
    }

除了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;
  }
}

如果您正在使用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 {
    // ...
}

相关内容

  • 没有找到相关文章

最新更新