spring中怎样优化第三方bean?

需求:将数据库连接四要素提取到properties配置文件,spring来加载配置信息并使用这些信息来完成属性注入。第三方bean属性优化的思路如下:

1.在resources下创建一个jdbc.properties(文件的名称可以任意)

2.将数据库连接四要素配置到配置文件中

3.在Spring的配置文件中加载properties文件

4.使用加载到的值实现属性注入

其中第3,4步骤是需要重点关注,具体是如何实现。

实现步骤

步骤1:准备properties配置文件

resources下创建一个jdbc.properties文件,并添加对应的属性键值对

bash 复制代码
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/spring_db
jdbc.username=root
jdbc.password=root

步骤2:开启context命名空间

在applicationContext.xml中开context命名空间

bash 复制代码
<?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/springcontext.xsd">
</beans>

步骤3:加载properties配置文件

在配置文件中使用context命名空间下的标签来加载properties配置文件

bash 复制代码
<context:property-placeholder location="jdbc.properties"/>

步骤4:完成属性注入

使用${key}来读取properties配置文件中的内容并完成属性注入

bash 复制代码
<?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/springcontext.xsd">
<context:property-placeholder location="jdbc.properties"/>
<bean id="dataSource" 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>

至此,读取外部properties配置文件中的内容就已经完成。

相关推荐
源码云商30 分钟前
阿博图书馆管理系统 Java+Spring Boot+MySQL 实战项目分享
java·spring boot·mysql
程序员Bears33 分钟前
Flask项目实践:构建功能完善的博客系统(含评论与标签功能)
后端·python·flask
zhou18536 分钟前
【最新】MySQL 5.6 保姆级安装详细教程
java·数据库·python·mysql·php
带刺的坐椅41 分钟前
100% 自主可控,Java Solon v3.3.1 发布(国产优秀应用开发基座)
java·spring·ai·信创·solon·mcp
孤寂大仙v1 小时前
【Linux笔记】——简单实习一个日志项目
java·linux·笔记
川石教育1 小时前
Grafana之Dashboard(仪表盘)
java·javascript·grafana·普罗米修斯
弥鸿1 小时前
RestFul操作ElasticSearch:索引与文档全攻略
后端·elasticsearch·restful
blues_C1 小时前
二、【环境搭建篇】:Django 和 Vue3 开发环境准备
后端·python·django·vue3·测试平台
工业互联网专业1 小时前
基于springboot+vue的病例管理系统
java·vue.js·spring boot·毕业设计·源码·课程设计·病例管理系统
Murphy_lx2 小时前
django回忆录(Python的一些基本概念, pycharm和Anaconda的配置, 以及配合MySQL实现基础功能, 适合初学者了解)
后端·python·pycharm·django