如何使用Spring Boot

时间:2017-08-31 16:36:18

标签: 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) {
        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")

我知道我们无法实现使用注释。我怎么能务实地做到这一点?

1 个答案:

答案 0 :(得分:0)

您可以使用Spring ResourceBundleMessageSource。它有助于加载外部属性。看看here

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