Spring加载properties文件
- 一、话不多说,直接上案例
- 1、创建jdbc.properties文件
- 2、开启context命名空间,加载properties配置文件
- 3、编写测试代码
- 4、测试结果
- 二、小结
一、话不多说,直接上案例
1、创建jdbc.properties文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/graduate
jdbc.username=root
jdbc.password=200226
- 格式:变量名=变量值
- 中间不要出现空格,虽然我们平常写代码都喜欢空格,感觉这样代码没有那么拥挤,看着更舒服一点,但是在该文件中不要出现多余的空格,因为可能会错误的认为空格也是值的一部分,导致取出的值错误。
- 变量名尽量也不要直接命名为"username"或者"password"这些,这些命名可能会和系统命名重复,在使用${}符取值时会优先取系统变量值。
2、开启context命名空间,加载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">
<!-- 1、开启context命名空间,需要添加上述和context有关的信息 -->
<!-- 2、使用context加载配置文件 -->
<context:property-placeholder location="jdbc.properties"/>
<!-- 3、使用${}动态获取值 -->
<bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
</beans>
- 开启context命名空间,需要加入第4、8、9行代码。添加后能够使用context相关标签。
- 加载"properties"文件需要使用到"context:property-placeholder",将该文件的地址存入"location"属性中。
- 在注入时,使用${}符获取。
3、编写测试代码
public class App {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
DruidDataSource druidDataSource = (DruidDataSource) context.getBean("druidDataSource");
System.out.println(druidDataSource);
}
}
4、测试结果
{
CreateTime:"2022-05-12 23:09:57",
ActiveCount:0,
PoolingCount:0,
CreateCount:0,
DestroyCount:0,
CloseCount:0,
ConnectCount:0,
Connections:[
]
}
- 依然能够正确获取到数据库对象。
二、小结
- 加载配置文件时需要使用"location"属性指定文件路径,其实上面使用的方式不是很规范。
<context:property-placeholder location="classpath:jdbc.properties"/>
这种方式更规范一点。
- 如果需要加载多个properties文件,可以以英文逗号进行分隔
<context:property-placeholder location="classpath:jdbc.properties,druid.properties"/>
或使用*号加载所有的配置文件
<context:property-placeholder location="classpath:*.properties"/>
- 如果想要加载jar包中的配置文件,可以使用,注意*号的个数和位置的不同
<context:property-placeholder location="classpath*:*.properties"/>
- 前面提到了properties文件中变量的命名问题,如果想要在使用${}符获取值时不加载系统属性,可以加上system-properties-mode=“NEVER” 解决。
<context:property-placeholder location="classpath*:*.properties" system-properties-mode="NEVER"/>
👉 以上就是文章的全部内容啦,诸佬如果有任何建议都可以提哦。