依赖注入-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 @   ShaunY  阅读(40)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示