如何使用Spring Boot使用动态文件读取外部属性



我想使用Spring

执行与以下代码相似的内容
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。它有助于加载外部属性。看看这里。

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

最新更新