1. 程式人生 > 其它 >Spring 配置資料來源-通過Bean配置 和Spring 載入配置檔案

Spring 配置資料來源-通過Bean配置 和Spring 載入配置檔案

//"com.alibaba.druid.pool.DruidDataSource"為資料來源的物件應用目錄
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
                <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
                <property name="url" value="jdbc:mysql://localhost:3306/music"></property>
                <property name="username" value="root"></property>
                <property name="password" value="123"></property>
        </bean>

使用

       ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        DataSource dataSource =(DataSource) app.getBean("dataSource");
        Connection connection = dataSource.getConnection();
        System.out.println(connection);

Spring 載入配置檔案

首先,需要引入context名稱空間和約束路徑:

名稱空間:xmlns:context="http://www.springframework.org/schema/context"
約束路徑:http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd

然後載入配置檔案,通過spel表示式 寫入屬性

         <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
       <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
                <property name="driverClassName" value="${jdbc.driver}"></property>
                <property name="url" value="${jdbc.url}"></property>
                <property name="username" value="${jdbc.username}"></property>
                <property name="password" value="${jdbc.password}"></property>
        </bean>