依赖注入-xml-引入外部属性文件

尚硅谷 Spring - 31

比较常见的引用外部属性的场景是引用 mysql

1. 加入依赖

<!--MySQL驱动-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.30</version>
</dependency>
<!--数据源-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.31</version>
</dependency>

2. 创建外部属性文件

比如 properties 格式的,定义了数据信息,包括用户名、密码、地址等

image

jdbc.user=root
jdbc.password=root
jdbc.url=jdbc:mysql://localhost:=3306/spring?serverTimezone=UTC
jdbc.driver=com.mysq1.cj.jdbc.Driver

3. 配置 Spring 配置文件

  1. 创建 spring 配置文件
  2. 引入 context 命名空间
  3. 引入属性文件:<context:property-placeholder>
  4. 使用表达式完成注入:使用 ${} 引用配置文件里的属性
<?xm1 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">
    <!--引入外部属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--完成数据库信息注入-->
    <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.user}"/>
	<property name="password" value="${jdbc.password}"/>
	<property name="driverClassName" value="${jdbc.driver}"/>
    </bean>
</beans>
posted @ 2023-07-15 14:11  ShaunY  阅读(49)  评论(0)    收藏  举报