Spring加载properties文件

Spring加载properties文件,第1张

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配置文件

<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">

    
    
    <context:property-placeholder location="jdbc.properties"/>
    
    <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"/>

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/915386.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存