PropertySourcesPlaceholderConfigurer的动态位置

时间:2013-03-01 14:40:31

标签: java spring properties

我有占位符的基于注释的bean配置。 在这个占位符的帮助下,我可以非常轻松地使用我想要的属性值。

@Bean
    public static PropertySourcesPlaceholderConfigurer initPlaceholder() {
        PropertySourcesPlaceholderConfigurer placeholder = new PropertySourcesPlaceholderConfigurer();
        placeholder.setLocation(new ClassPathResource("some.properties"));
        placeholder.setIgnoreUnresolvablePlaceholders(true);

        return placeholder;
    }

如何使用$ {some.properties}动态值设置此占位符?

placeholder.setLocation(new ClassPathResource(ANY_PROPERTIES));

我无法使用initPlaceholder(String属性)...

1 个答案:

答案 0 :(得分:0)

我对此做了什么是创建我自己的PropertyPlaceHolder(以获取外部属性文件)

public class MyPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

public static final String ANY_PROPERTY = "ANY_PROPERTY";

private static final Log LOG = LogFactory.getLog(MyPropertyPlaceholderConfigurer.class);

@Override
protected void loadProperties(Properties props) throws IOException {

    String anyProperty = System.getProperty(ANY_PROPERTY);

    if (StringUtils.isEmpty(anyProperty)) {
        LOG.info("Using default configuration");
        super.loadProperties(props);

    } else {
        LOG.info("Setting HDFS LOCATION PATH TO : " + anyProperty);

        try {
            Path pt = new Path(anyProperty);
            Configuration conf = new Configuration();
            conf.set(FileSystem.FS_DEFAULT_NAME_KEY, anyProperty);
            FileSystem fs = FileSystem.get(conf);
            FSDataInputStream fileOpen = fs.open(pt);
            BufferedReader br = new BufferedReader(new InputStreamReader(fileOpen));
            props.load(br);
        } catch (Exception e) {
            LOG.error(e);
        }
    }

}
相关问题