~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
开发工具与关键技术:myEclipse,Spring加载属性文件
撰写时间:2020-05-08
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
说明:以下以最简单的加载文件做一个demo,就是加载连接数据库的连接词进行加载。(就是把一些频繁修改的值,单独提取到外部的属性文件中,有利于环境部署时比较方便。)
什么是环境部署:就是项目部署在服务器
如何加载属性文件
第一步:首先要有个文件(那就是连接数据库的连接词属性文件。)
新建一个file命名为xx.properties(这是属性文件的后缀),建在src下即可。然后编写内容。
第二步:需要使用到上下文命名空间(context:参数命名空间也叫属性命名空间)也就是黄色字体的配置
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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" > |
第三步:接下来就是用到一个非常简单的标签,那就context:property-override
代码:加载属性文件。
<context:property-override location="classpath:db.properties"/>
classpath:就是在类路径下开始寻找,否则就要在项目下寻找。写法就比较麻烦了如果加载多个属性文件就在后面加个逗号,然后写文件路径 :location="classpath:db.properties,classpath:......"
第四步:加载完成之后,将提取出的值,再写回应该在的地方。
代码:未提取前代码
<!-- 数据源封装类 ,数据源:获取数据库连接,spring -jdbc jar中-->
<bean id="dataSouce" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/demo"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
提取后,就是将属性文件中命名填写回其中
<!-- 数据源封装类 ,数据源:获取数据库连接,spring -jdbc jar中-->
<bean id="dataSouce" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.password}"></property>
<property name="password" value="${jdbc.username}"></property>
</bean>