Spring引入外部properties文件

本文介绍了如何在Spring中引入外部properties文件,特别是在环境变化时避免将配置打包进war。文章探讨了使用`<context:property-placeholder>`标签的`location`属性结合`file:`, `http:`, `ftp:`前缀以及利用Spring的EL表达式引用系统变量的方法,通过实例展示了如何从Tomcat工作目录的特定路径加载数据库配置文件。" 127369348,5691934,Android:检测字符串是否含字母数字,"['Android开发', '数据结构', '字符串处理']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、背景:Spring配置文件需要通过context:property-placeholder标签或者PropertyPlaceholderConfigurer类来引入classpath路径下的properties文件,示例如下:

<context:property-placeholder location="classpath:jdbc.properties" />
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations" value="classpath:jdbc.properties"/>
</bean>

但像数据库配置这种随环境变化的文件我们并不想打到war中,而是希望引入war包外的文件。

2、方案context:property-placeholder标签的location属性还提供了file:http:ftp:三种前缀,分别通过文件路径、HTTP资源和FTP资源引入文件,详见Spring官方文档。同时Spring支持#{systemProperties['config.location']}EL表达式,来引入自定义的系统变量config.location,详见Spring官方文档

3、示例:我的数据库配置放到了Tomcat工作目录的自定义目录custom_config下,名为jdbc.properties,通过自定义Listener将custom_config的绝对路径写到系统变量中,然后在Spring配置文件通过file:前缀和#{systemProperties['config.location']}来找到jdbc.properties
Tomcat目录

public class ConfigLocationListener implements ServletContextListener {
    private static Logger log = LoggerFactory.getLogger(ConfigLocationListener.class);

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        log.info("init begin");

        // 设置配置文件路径
        String configFilePath = System.getProperty("catalina.home") + "/custom_config/";

        // 设置配置文件路径的系统变量
        System.setProperty("config.location", configFilePath);

        log.info("init end");
    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        log.info("destroy begin");
        log.info("destroy end");
    }

}
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <context:property-placeholder location="file:#{systemProperties['config.location']}jdbc.properties" />

    ... ...

</beans>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值