一、引言
很多小伙伴看到标题,咦,Bean使用外部属性配置文件是啥? 干啥用的?
小编先问下,在你们开发项目当中,后缀名为properties的文件,看见过没?
什么?没看见过? 别扯了,怎么可能没看过。嗯嗯行,就算你们没使用过,小编简单介绍一下。
以properties扩展名的文件,一般称之为属性配置文件,一般存放数据库连接信息,或者项目一些存放的配置。
给你们看下存放格式,以下是数据库的连接信息,一般存放在项目的配置文件目录下
#mysql database settings
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://127.0.0.1\:3360/spring?useUnicode\=true&characterEncoding\=utf-8&zeroDateTimeBehavior\=convertToNull&transformedBitIsBoolean\=true
jdbc.username=root
jdbc.password=HuNyECMuA0c//G6MaRMU1wsg8j8JzgbU6kmXS+Gbo+qCQ5M/9/CQIFZXG0USgl5EOi43JXVtAEgh0SitVgRYIQ==
#dbcp settings
dbcp.maxIdle=5
dbcp.maxActive=40
二、具体操作
步骤一:创建一个以.properties结尾的文件,小编创建一个car.properties文件,写入了以下配置
brand=奥迪
origin=德国
price=10000000
步骤二:先要导入context的命名空间,然后导入属性配置文件,因为配置文件可能不止一个,所以采用了*来匹配所有的,并且设置来字符集,不然独取出来的中文是乱码的,获取值使用${}的方式即可。
<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-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--先要导入context的命名空间-->
<!-- 导入属性文件-->
<context:property-placeholder location="classpath:*.properties" file-encoding="UTF-8"/>
<bean id="car" class="com.spring.fuor.Car" scope="singleton">
<property name="brand" value="${brand}"></property>
<property name="origin" value="${origin}"></property>
<property name="price" value="${price}"></property>
</bean>
</beans>
步骤三:最后看看结果呗,省的说我骗你们。
public static void main(String[] args) {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("applicationContext-four.xml");
Car car = (Car)beanFactory.getBean("car");
System.out.println(car.toString());
}
十月 29, 2018 10:38:35 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@246b179d: startup date [Mon Oct 29 22:38:35 CST 2018]; root of context hierarchy
十月 29, 2018 10:38:35 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [applicationContext-four.xml]
十月 29, 2018 10:38:35 下午 org.springframework.context.support.PropertySourcesPlaceholderConfigurer loadProperties
信息: Loading properties file from file [/Users/yaoyaoyao/procute/spring-parents/spring-DI/target/classes/car.properties]
Car{brand='奥迪', origin='德国', price=10000000}
三、背景
小编再和你们分享相关知识,顺便总结一下
在配置文件里配置Bean时,有时需要在Bean的配置里混入一些其他配置,例如数据库配置信息,文件路径等等,
Sprin提供了一个PropertyPlaceholderConfigurer的BeanFactory后置处理器,这个处理器允许用户将Bean配置的部分内容写到属性文件中去,可以在Bean配置文件里面采用${}形式来引用,PropertyPlaceholderConfigurer将会从属性配置文件加载属性,并使用这些属性来替换变量。
要洗洗睡了,good night!!!