Spring --- IOC 容器 之 Bean管理XML方式(外部属性文件)

    通过xml方式管理bean,是有效的。但是当遇到属性值较多的情况,只在xml文件中进行配置显然很麻烦,也不便于管理,缺少灵活性。这时,需要用到外部属性文件。例如数据库连接信息,放在外部属性文件管理远比直接写死在xml文件里面好的多。关于bean对象的创建,小编在前面的文章:Spring — IOC 容器 之 Bean管理XML方式(创建对象)
有详细介绍,有需要的可以回去翻看一下。今天,小编介绍一下bean管理xml方式中的外部属性文件的使用。

1,外部属性文件:jdbc.properties

prop.driverName=com.mysql.cj.jdbc.Driver
prop.url=jdbc:mysql://localhost:3306/kpl_work
prop.username=root
prop.password=root

2,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: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">

<!--    xmlns:context="http://www.springframework.org/schema/context"
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
        这两端配置是自定义的上下文,用于下面的外部文件引入
-->

<!--    引入外部属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

<!--    定义bean-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${prop.driverName}"/>
        <property name="url" value="${prop.url}"/>
        <property name="username" value="${prop.username}"/>
        <property name="password" value="${prop.password}"/>
    </bean>

3,测试:

public class BeanTest {
    @Test
    public void test7(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("com/chaoge/nacos/demo/test/spring/beanConfig/BeanConfig.xml");
        DruidDataSource dataSource = context.getBean("dataSource", DruidDataSource.class);
        System.out.println(dataSource.getUrl());
        System.out.println(dataSource.getUsername());
        System.out.println(dataSource.getPassword());
    }
}

4,输出:

D:\jdk\jdk1.8.0_171\bin\java.exe
jdbc:mysql://localhost:3306/kpl_work
root
root
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

皮皮克克

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值