一、背景
最近,在项目开发的过程中,遇到需要在properties文件中定义一些自定义的变量,以供java程序动态的读取,修改变量,不再需要修改代码的问题。就借此机会把Spring+SpringMVC+Mybatis整合开发的项目中通过java程序读取properties文件内容的方式进行了梳理和分析,现和大家共享。
二、项目环境介绍
Spring 4.2.6.RELEASE
SpringMvc 4.2.6.RELEASE
Mybatis 3.2.8
Maven 3.3.9
Jdk 1.7
Idea 15.04
三、五种实现方式
方式1.通过context:property-placeholder加载配置文件jdbc.properties中的内容
<context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/>
上面的配置和下面配置等价,是对下面配置的简化
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="ignoreUnresolvablePlaceholders" value="true"/> <property name="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> </bean>
注意:这种方式下,如果你在spring-mvc.xml文件中有如下配置,则一定不能缺少下面的红色部分,关于它的作用以及原理,参见另一篇博客:context:component-scan标签的use-default-filters属性的作用以及原理分析
<!-- 配置组件扫描,springmvc容器中只扫描Controller注解 --> <context:component-scan base-package="com.hafiz.www" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
方式2.使用注解的方式注入,主要用在java代码中使用注解注入properties文件中相应的value值
<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <!-- 这里是PropertiesFactoryBean类,它也有个locations属性,也是接收一个数组,跟上面一样 --> <property name="locations"> <array> <value>classpath:jdbc.properties</value> </array> </property> </bean>
方式3.使用util:properties标签进行暴露properties文件中的内容
<util:properties id="propertiesReader" location="classpath:jdbc.properties"/>
注意:使用上面这行配置,需要在spring-dao.xml文件的头部声明以下红色的部分
<beans xmlns