Java 如何使用Spring Boot读取动态文件的外部属性
我想使用Spring执行类似于以下代码的操作Java 如何使用Spring Boot读取动态文件的外部属性,java,spring,spring-mvc,Java,Spring,Spring Mvc,我想使用Spring执行类似于以下代码的操作 class MyPropotypeBean { /* We can not for static file name like * @ConfigurationProperties(prefix = "abcd", locations = "file:conf/a2z.properties") */ public MyPropotypeBean(String propFileLocation) {
class MyPropotypeBean {
/* We can not for static file name like
* @ConfigurationProperties(prefix = "abcd", locations = "file:conf/a2z.properties")
*/
public MyPropotypeBean(String propFileLocation) {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream(propFileLocation);
prop.load(input);
gMapReportUrl = prop.getProperty("gMapReportUrl");
} catch (IOException ex) {
ex.printStackTrace();
} finally {
...
}
}
}
我希望propFileLocation动态注入类似于以下内容的内容
@ConfigurationProperties(prefix = "abcd", locations = "file:conf/" + propFileLocation + ".properties")
我知道我们无法通过注释来实现。我怎样才能实用呢?您可以使用Spring
ResourceBundleMessageSource
。它有助于加载外部属性。看一看
可能在不同的静态属性文件中有动态文件列表?使用环境,Luke(环境变量或某些属性)文件列表是动态的,每个原型bean必须根据文件属性具有不同的值。环境变量可以包含多个prop文件名,我们需要创建相同数量的原型bean。谢谢您的回复,但这不是我想要的。我想通过动态注入属性文件来创建原型bean。在我的例子中,解决方案的更好方法是遵循
@Bean@Resource public Properties config(String propFileLocation)抛出IOException{return Properties loaderutils.loadProperties(new classpathrource(propFileLocation));}
@Value("${file.directory}")
private String propFileLocation;
//getters and setters
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasenames("file:conf/"+propFileLocation);
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}