【Spring IOC容器】引入外部属性文件



引入外部属性文件

在很多时候,我们的类中属性可能不止一个,那么我们按照xml方式进行配置的时候就需要多次使用property标签进行属性的注入,一旦属性多了,使用起来就会很麻烦。那么我们可以将一些固定的值提前配置好,使用时直接引用就行。常见的就是针对数据库操作时的连接!我们可以将数据库名称、用户名、密码、url等提前配置好,然后使用的时候直接引入即可。

① 直接配置数据库信息

Ⅰ.配置德鲁伊连接池

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--  直接配置数据库连接池  -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!--   配置数据库信息     -->
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306:/test01"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>
</beans>

Ⅱ.引入德鲁伊连接池依赖 jar 包

在这里插入图片描述

返回顶部


② 通过外部文件配置数据库连接池

Ⅰ.创建外部属性properties 格式文件

  • 文件中写数据库信息
prop.driverClass=com.mysql.jdbc.Driver
prop.url=jdbc:mysql://localhost:3306/test01
prop.userName=root
prop.password=123456

Ⅱ.把外部 文件引入spring 配置文件中

  • 引入 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">
  • 在 spring 配置文件使用标签引入外部属性文件
    <!--  通过引入外部属性文件  -->
    <context:property-placeholder location="classpath:外部属性文件/jdbc.properties"></context:property-placeholder>
    <!--  直接配置数据库连接池  -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!--   配置数据库信息     -->
        <property name="driverClassName" value="${prop.driverClass}"></property>
        <property name="url" value="${prop.url}"></property>
        <property name="username" value="${prop.userName}"></property>
        <property name="password" value="${prop.password}"></property>
    </bean>
</beans>

返回顶部


猜你喜欢

转载自blog.csdn.net/qq_45797116/article/details/113573258