Spring使用外部属性文件
一、在 Spring Config 文件中配置 Bean 时,有时候需要在 Bean 的配置里添加 系统部署的细节信息, 如文件路径,数据源配置信息。而这些部署细节实际上需要在配置文件外部来定义。
二、Spring 提供了一个 PropertyPlaceholderConfigurer 的 BeanFactory 后置处理器。这个处理器允许用户将 Bean 的配置部分内容外移到属性文件中,然后可以在 Bean 的配置文件
里使用形式为 ${var}的变量,PropertyPlaceholderConfigurer 从属性文件里加载属性,并使用这些属性来替换变量。
三、Spring 还允许在属性文件中使用 ${key},以属性间的互相引用。
四、使用:需要注册 PropertyPlaceholderConfigurer 。通过 <context:property-placeholder location="props.properties"/> 这种方式来指定属性文件。
<?xml version="1.0" encoding="UTF-8"?> <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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="root"/> <property name="password" value="lgh123"/> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?user=root&password=lgh123&useUnicode=true&characterEncoding=UTF8&useSSL=true"/> </bean>--> <!--导入属性文件--> <context:property-placeholder location="classpath:db.properties"/> <!--使用外部的属性文件的属性配置--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${user}"/> <property name="password" value="${password}"/> <property name="driverClass" value="${driverClass}"/> <property name="jdbcUrl" value="${jdbcUrl}"/> </bean> </beans>
db.properties
user=root password=lgh123 driverClass=com.mysql.jdbc.Driver jdbcUrl=jdbc:mysql://localhost:3306/test?user=root&password=lgh123&useUnicode=true&characterEncoding=UTF8&useSSL=true
测试:
package com.xiya.spring.beans.properties; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import javax.sql.DataSource; import java.sql.SQLException; /** * Created by N3verL4nd on 2017/3/22. */ public class Main { public static void main(String[] args) throws SQLException { ApplicationContext context = new ClassPathXmlApplicationContext("beans-properties.xml"); DataSource dataSource = (DataSource) context.getBean("dataSource"); System.out.println(dataSource.getConnection()); } }
Keep it simple!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
2013-03-22 链表的逆置
2013-03-22 已知顺序表L递增有序,写一算法,将X插入到线性表的适当位置,以保持线性表的有序