美文网首页
spring中怎样优化第三方bean?

spring中怎样优化第三方bean?

作者: 鹤子青云上 | 来源:发表于2023-07-18 18:03 被阅读0次

    需求:将数据库连接四要素提取到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/spring�context.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/spring�context.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配置文件中的内容就已经完成。

    相关文章

      网友评论

          本文标题:spring中怎样优化第三方bean?

          本文链接:https://www.haomeiwen.com/subject/geonudtx.html