spring 引入外部配置文件propertice

spring 引入外部配置文件propertice

引用外部配置文件是为了更好的阅读与维护
在这里只讲述context方法引入外部配置文件

1、spring.xml的配置

<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" 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">

2、配置校验文件
校验文件配置
3、db.propertice文件内容

jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.username=mybatis
jdbc.password=a

4、引入外部的Properties属性文件

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

5、spring配置数据源

    <!-- ${xxxx}:表示动态引用外部的配置文件 -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

6、测试
pom.xml中引用Junit包

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

测试类:

import static org.junit.Assert.*;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class test {
    @Test
    public void testConn() {
        ApplicationContext ac=new ClassPathXmlApplicationContext("spring2.xml");
        DataSource d=(DataSource) ac.getBean("dataSource");
        try {
            Connection con=d.getConnection();
            System.out.println(con);
            assertNotNull(con);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

返回结果输出,并且Junit结果显示正确:

25927067, URL=jdbc:oracle:thin:@localhost:1521:orcl, UserName=MYBATIS, Oracle JDBC driver

如果需要引入多个配置文件

<!-- 通过context:property-placeholde加载多个配置文件 只需在第1.2步中将多个配置文件以逗号分隔即可 
<context:property-placeholder 
        location="classpath:jdbc.properties,classpath:XXX.properties"/> -->

配置数据源时也可采用这种方式

<property name="password">
    <value>${jdbc.password}</value>
</property>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值