首页 > 技术文章 > Spring-Bean配置-引用外部属性文件

orzjiangxiaoyu 2020-08-16 11:37 原文

在web应用中数据库连接池作为单实例对象是最好的

以Druid数据库连接池配置为例

第一种方式:直接配置德鲁伊连接池

   <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="password" value="root"></property>
        <property name="username" value="root"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/test"></property>
    </bean>

(2)测试

    @Test
    public void test1()
    {
        ApplicationContext context=new ClassPathXmlApplicationContext("bean9.xml");
        DruidDataSource dataSource = context.getBean("dataSource", DruidDataSource.class);
        try {
            Connection conn=dataSource.getConnection();
            System.out.println(conn);

        }
        catch (Exception e)
        {
           e.printStackTrace();
        }
    }

(3)结果

com.mysql.jdbc.JDBC4Connection@6eb2384f

第二种方式:通过引入外部属性文件配置德鲁伊连接池

(1)外部属性文件(mysqljdbc.properties)

jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode\=true&characterEncoding\=utf-8
jdbc.username=root
jdbc.password=root
jdbc.driverClassName=com.mysql.jdbc.Driver

(2)Bean配置文件

  注:需要引入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:p="http://www.springframework.org/schema/p"
       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="mysqljdbc.properties"></context:property-placeholder>
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="driverClassName" value="${jdbc.driverClassName}"></property>
    </bean>

</beans>

(3)测试

public class Test1 {
    @Test
    public void test1()
    {
        ApplicationContext context=new ClassPathXmlApplicationContext("bean9.xml");
        DruidDataSource dataSource = context.getBean("dataSource", DruidDataSource.class);
        try {
            Connection conn=dataSource.getConnection();
            System.out.println(conn);

        }
        catch (Exception e)
        {
           e.printStackTrace();
        }
    }
}

(4)结果

com.mysql.jdbc.JDBC4Connection@691939c9

 

推荐阅读