通过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