[英]@PropertySource in a Jar for an external file on the classpath
[英]classpath wildcard in @PropertySource
我正在使用 Spring Java 配置来创建我的 bean。 但是这个 bean 对 2 个应用程序是通用的。 两者都有一个属性文件 abc.properties 但具有不同的类路径位置。 当我把明确的类路径像
@PropertySource("classpath:/app1/abc.properties")
然后它可以工作但是当我尝试使用通配符时
@PropertySource("classpath:/**/abc.properties")
那么它不起作用。 我尝试了多种通配符组合,但仍然无法正常工作。 通配符在@ProeprtySource
是否@ProeprtySource
是否还有其他方法可以读取标记为@Configurations
属性。
@PropertySource API: Resource location wildcards (eg **/*.properties) are not permitted; each location must evaluate to exactly one .properties resource.
Resource location wildcards (eg **/*.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 {
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.