Spring - 加载properties文件

211 阅读1分钟

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!--开启context命名空间-->
<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命名空间,加载指定的properties文件 system-properties-mode="NEVER"表示不加载系统属性-->
<context:property-placeholder location="jdbc.properties" system-properties-mode="NEVER"/>
   <!--如果有多个配置文件需要加载 以下三种方式自行选择-->
   <!--指定加载某个文件-->
<!--<context:property-placeholder location="jdbc.properties,jdbc2.properties" system-properties-mode="NEVER"/>-->
   <!--加载工程所有的properties文件-->
<!--<context:property-placeholder location="classpath:*properties" system-properties-mode="NEVER"/>-->
   <!--加载工程所有的properties文件 包括工程所依赖的jar包-->
<!--<context:property-placeholder location="classpath*:*properties" system-properties-mode="NEVER"/>-->


   <bean id="Druid" class="com.alibaba.druid.pool.DruidDataSource">
      <!--使用${}资源占位符读取加载属性值-->
      <property name="driverClassName" value="${jdbc.driverClassName}"/>
      <property name="url" value="${jdbc.url}"/>
      <property name="username" value="${jdbc.userName}"/>
      <property name="password" value="${jdbc.password}"/>
   </bean>

</beans>

properties文件

jdbc.driverClassName = com.mysql.jdbc.Driver jdbc.url = jdbc:mysql://localhost:3306/db1 jdbc.userName = root jdbc.password = 1234

操作步骤及加载properties文件的方式

image.png

image.png