快捷搜索:  汽车  科技

java读取properties方法(五种方式让你在java中读取properties文件内容不再是难题)

java读取properties方法(五种方式让你在java中读取properties文件内容不再是难题)Idea 15.04 Jdk 1.7 SpringMvc 4.2.6.RELEASE Mybatis 3.2.8 Maven 3.3.9

一、背景

最近,在项目开发的过程中,遇到需要在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值

6.项目GitHub地址

https://github.com/hafizzhang/SSM/branches 页面下的propertiesConfigurer分支。

7.测试结果

第一种方式

java读取properties方法(五种方式让你在java中读取properties文件内容不再是难题)(1)

第二种方式

java读取properties方法(五种方式让你在java中读取properties文件内容不再是难题)(2)

第三种方式

java读取properties方法(五种方式让你在java中读取properties文件内容不再是难题)(3)

第四种方式

java读取properties方法(五种方式让你在java中读取properties文件内容不再是难题)(4)

第五种方式

java读取properties方法(五种方式让你在java中读取properties文件内容不再是难题)(5)

六、总结

通过本次的梳理和测试,我们理解了Spring和SpringMVC的父子容器关系以及context:component-scan标签包扫描时最容易忽略的use-default-filters属性的作用以及原理。能够更好地定位和快速解决再遇到的问题。总之,棒棒哒~~~

猜您喜欢: