【问题标题】:Dynamic location for PropertySourcesPlaceholderConfigurerPropertySourcesPlaceholderConfigurer 的动态位置
【发布时间】:2013-03-01 14:40:31
【问题描述】:

我有占位符的基于注释的 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 property)...

【问题讨论】:

  • 那么,您想在不使用占位符的情况下获得财产吗?在这种情况下,我认为弹簧配置文件会更好......(根据某些配置文件选择属性文件)。

标签: java spring properties


【解决方案1】:

对此我所做的是创建自己的 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);
        }
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 2014-12-03
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    • 2016-07-19
    • 2011-05-05
    相关资源
    最近更新 更多