当前位置: 首页 > news >正文

spring中怎样优化第三方bean?

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

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

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

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

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

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

实现步骤

步骤1:准备properties配置文件

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

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命名空间

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

<context:property-placeholder location="jdbc.properties"/>

步骤4:完成属性注入

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

<?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配置文件中的内容就已经完成。

http://www.lryc.cn/news/68751.html

相关文章:

  • 8分钟的面试,我直呼太变态了......
  • 别去外包,干了3年,彻底废了......
  • ipa如何安装到iphone
  • 照片从安卓手机中消失了?让他们恢复回来的几个方法请收好
  • 哪个年龄段人群喜欢养宠物?18-25岁占比最高,达31%
  • 使用Apache POI数据导出及EasyExcel进行十万、百万的数据导出
  • 八种故障排障思路
  • JavaScript全解析——this指向
  • MySQL中ON DUPLICATE KEY UPDATE和REPLACE INTO区别
  • 37本国产SCI期刊推荐!涵盖9大领域,建议收藏!②
  • 掌握无缝云迁移方法的数据集成
  • unity 3种办法实现血条效果并实现3d世界血条一直看向摄像机
  • Jenkins流水线整合k8s实现代码自动集成和部署
  • @PulsarConsumer注解2
  • AIGC 综述 2023:A History of Generative AI from GAN to ChatGPT
  • 【JOSEF约瑟 JDZS-1202B 可调断电延时中间继电器 精度高、延时宽、】
  • UNeXt:基于MLP的快速医学图像分割网络
  • 软路由简述
  • python 生成设施农用地各类材料,并调用python2进行出图
  • html - 多媒体标签(video)、音频标签(audio)
  • 希望计算机专业同学都知道这些博主
  • LeetCode 416 分割等和子集
  • 韦东山Linux驱动入门实验班(2)hello驱动---驱动层与应用层通讯,以及自动产生设备节点
  • 小程序技术,打开跨端管理的思路,提高客户满意度和忠诚度
  • Jmeter的Content-Type设置方式
  • SQL语法
  • 面试题30天打卡-day30
  • learn_C_deep_11 (深刻理解整形提升、左移和右移规则、花括号、++和--操作、表达式匹配:贪心算法)
  • 十个高质量工具网站推荐,AI自动抠图换背景,任意背景自动融合
  • 小红的好数组陡峭值之和