PropertyPlaceholderConfigurer:使用外部属性文件 [英] PropertyPlaceholderConfigurer: Use external properties file

查看:302
本文介绍了PropertyPlaceholderConfigurer:使用外部属性文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何配置PropertyPlaceholderConfigurer以使用属性文件相对(一些目录向上)战争?

How to configure PropertyPlaceholderConfigurer to use properties files relative (some directories up) to the war?

我们有多次运行战争,每个战争应该读取其配置例如 ../../ etc / db.properties

We have running a war multiple times and each war should read its configuration for example from ../../etc/db.properties.

更新:

是的,属性文件在战争之外。目录结构是:

Yes, the properties files are outside the war. The directory structure is:

/htdocs/shop/live/apache-tomat/webapps/shop.war
应为
/htdocs/shop/live/etc/db.properties

/htdocs/shop/test/apache-tomat/webapps/shop.war

/htdocs/shop/test/etc/db.properties

推荐答案

最后,我们引入了一个新的资源类型relative::

Finally, we have introduced a new resource type "relative:":

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="ignoreResourceNotFound" value="true" />
    <property name="locations">
        <list>
            <value>classpath:db.properties</value>
            <value>relative:../../../etc/db.properties</value>
        </list>
    </property>
</bean>

我们扩展了XmlWebApplicationContext以注入自定义资源处理:

We have extended XmlWebApplicationContext to inject custom resource handling:

public class Context extends XmlWebApplicationContext {
    @Override
    public Resource getResource(String location) {
        if (location.startsWith(RelativeResource.RELATIVE_URL_PREFIX)) {
            String relativePath = location.substring(RelativeResource.RELATIVE_URL_PREFIX.length());
            return new RelativeResource(getServletContext(), relativePath);
        }
        return super.getResource(location);
    }
}

这是相对的资源类:

public class RelativeResource extends AbstractResource {
    public static final String RELATIVE_URL_PREFIX = "relative:";

    private final ServletContext servletContext;
    private final String relativePath;

    public RelativeResource(ServletContext servletContext, String relativePath) {
        this.servletContext = servletContext;
        this.relativePath = relativePath;
    }

    @Override
    public String getDescription() {
        return "RelativeResource [" + relativePath + "]";
    }

    @Override
    public boolean isReadable() {
        return true;
    }

    @Override
    public boolean isOpen() {
        return true;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        String rootPath = WebUtils.getRealPath(servletContext, "/");
        if (!rootPath.endsWith(File.separator)) rootPath += File.separator;
        String path = rootPath + relativePath;
        return new FileInputStream(path);
    }

}

这篇关于PropertyPlaceholderConfigurer:使用外部属性文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆