Spring中你不得不知的各种Utils

在Java开发过程中,我们会用到很多工具类来为我们项目开发做工作,同样,Spring板块中,也有很多工具类,他们有些是专门提供给了框架使用,有些也是提供了外接使用方法。使用适当的工具,让项目事半功倍。
前言

Spring的工具类都是以Utils结尾,所以要查看这些工具类,只需要在API文档中查询所有*Utils即可,可以看到有多达几十个。其中有我们非常熟悉的org.springframework.util.StringUtils,有用到过的org.springframework.aop.support.AopUtils,还有可能没有听过的org.springframework.core.annotation.AnnotatedElementUtils等等。后面我们会选择十来个有用的Utils,给大家展示一下Spring中的工具类的有用和常用方法。

org.springframework.core.io.support.PropertiesLoaderUtils

我们今天第一个介绍的是PropertiesLoaderUtils,这个工具类主要是针对Properties文件的加载操作,在Spring对.properties文件和.factories文件的操作都有使用到。

先来简单看看这个类提供的有用方法:

  • Properties loadProperties(Resource resource) throws IOException:从一个资源文件加载Properties;
  • Properties loadProperties(EncodedResource resource) throws IOException:加载资源文件,传入的是提供了编码的资源类(EncodedResource);和上面方法基本一致;
  • void fillProperties(Properties props, Resource resource) throws IOException:从一个资源类中加载资源,并填充到指定的Properties对象中;
  • void fillProperties(Properties props, EncodedResource resource)
    throws IOException:从一个编码资源类中加载资源,并填充到指定的Properties对象中;和上面方法基本一致;
  • Properties loadAllProperties(String resourceName) throws IOException:根据资源文件名称,加载并合并classpath中的所有资源文件;
  • Properties loadAllProperties(String resourceName, ClassLoader classLoader) throws IOException:从指定的ClassLoader中,根据资源文件名称,加载并合并classpath中的所有资源文件;

方法不是很多,而且共性较大,我们就从最简单的Properties loadProperties(Resource resource)开始。

loadProperties

测试方法很简单,我们首先准备一个test.properties文件,放到resources下面:

key=value

key2=\u4E2D\u6587

完成代码:

@Test

public void testLoadPropertiesResource() throws Exception {

????Properties ret = PropertiesLoaderUtils

????????????.loadProperties(new ClassPathResource("test.properties"));

????assertEquals("value", ret.getProperty("key"));

????assertEquals("中文", ret.getProperty("key2"));

}

测试完成。没有太大难度; 但是,其实Properties对象不仅仅支持.properties文件,还支持XML格式的资源配置文件。先来看看Properties对象对XML类型资源文件的DTD定义(http://java.sun.com/dtd/properties.dtd):

<!--

???Copyright 2006 Sun Microsystems, Inc.??All rights reserved.

??-->

<!-- DTD for properties -->

<!ELEMENT properties ( comment?, entry* ) >

<!ATTLIST properties version CDATA #FIXED "1.0">

<!ELEMENT comment (#PCDATA) >

<!ELEMENT entry (#PCDATA) >

<!ATTLIST entry key CDATA #REQUIRED>

那么我们就可以有以下测试。创建一个text.xml文件在classpath下:

<?xml version="1.0" encoding="UTF-8"?>??

<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"&gt;

<properties>

????<comment>一些自定义说明</comment>

????<entry key="key">value</entry>

????<entry key="key2">中文</entry>

</properties>

完成测试代码:

@Test

public void testLoadPropertiesResourceXml() throws Exception {

????Properties ret = PropertiesLoaderUtils

????????????.loadProperties(new ClassPathResource("test.xml"));

????assertEquals("value", ret.getProperty("key"));

????assertEquals("中文", ret.getProperty("key2"));

}

测试通过。当然,我们是非常不建议使用XML的方式来做配置的。

接下来使用EncodeResource来测试,EncodeResource在Resource上增加了字符编码设置。同样使用之前的test.properties:

@Test

public void testLoadPropertiesEncodedResource() throws Exception {

????Properties ret = PropertiesLoaderUtils.loadProperties(

????????????new EncodedResource(new ClassPathResource("test.properties"),

????????????????????"UTF-8"));

????assertEquals("value", ret.getProperty("key"));

????assertEquals("中文", ret.getProperty("key2"));

}

可以看到,只是在之前的ClassPathResource基础之上包装了UTF-8字符编码的EncodeResource;

loadAllProperties

loadProperties方法,从当前classpath下加载properties文件,如果使用loadAllProperties,可以从当前classpath下加载所有的相同名称的properties文件,并执行合并。

来完成一个测试。把上一个例子中的test.properties文件保留,放到src/main/resources中;然后在src/test/resources目录下再创建一个test.properties文件,内容为:

key3=value

测试代码:

@Test

public void testLoadAllPropertiesString() throws Exception {

????Properties ret = PropertiesLoaderUtils

????????????.loadAllProperties("test.properties");

????assertEquals("value", ret.getProperty("key"));

????assertEquals("value", ret.getProperty("key3"));

}

执行测试通过;可以看到,main下的test.properties和test下的test.properties都被识别并执行了合并;那如果在test/resources中的test.properties中增加

key=update

再次执行测试,仍然通过,说明在多个配置文件中如果有重复key,最近的classpath为准(比如当前应用的properties内容会优先于jar包中的properties)

但是,如果这种情况下,使用loadProperties方法,那么只会加载到test/resources中的test.properties;这个结果可以对loadAllProperties有更深刻理解。

fillProperties

fillProperties方法其实是loadProperties方法的真正调用方法。先来看看测试代码:

@Test

public void testFillPropertiesPropertiesResource() throws Exception {

????Resource res = new ClassPathResource("test.properties");

????Properties ret = new Properties();

????PropertiesLoaderUtils.fillProperties(ret, res);

????assertEquals("value", ret.getProperty("key"));

}

使用非常简单。

我们来看一下loadProperties方法的源代码:

/**

?* Load properties from the given EncodedResource,

?* potentially defining a specific encoding for the properties file.

?* @see #fillProperties(java.util.Properties, EncodedResource)

?*/

public static Properties loadProperties(EncodedResource resource) throws IOException {

????Properties props = new Properties();

????fillProperties(props, resource);

????return props;

}

可以看到,其实调用的就是fileProperties方法,而这个方法的实现其实也很简单:

public static void fillProperties(Properties props, EncodedResource resource)

????????throws IOException {

????fillProperties(props, resource, new DefaultPropertiesPersister());

}

代理给了fillProperties(Properties props, EncodedResource resource, PropertiesPersister persister)方法;只是最后一个参数是一个PropertiesPersister,抽取了一个统一的从XML或者properties资源加载和装载接口;来看看具体实现(我只保留了最基本的关键代码):

static void fillProperties(Properties props, EncodedResource resource, PropertiesPersister persister)

????????throws IOException {

????InputStream stream = null;

????Reader reader = null;

????try {

????????String filename = resource.getResource().getFilename();

????????//如果是XML文件,

????????if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) {

????????????stream = resource.getInputStream();

????????????persister.loadFromXml(props, stream);

????????}else {

????????????stream = resource.getInputStream();

????????????persister.load(props, stream);

????????}

????}finally {

????????//close方法

????}

}

可以看到,其实就是调用了PropertiesPersister的loadFromXml和load方法来分别加载XML或properties;

如果再往下看,有兴趣的童鞋可以看看DefaultPropertiesPersister的相关的这两个方法,其实核心还是使用Properties对象的load和loadFromXML方法完成的。

小结
propertiesloaderutils提供了加载的便捷操作,并且在spring工具类中还有更多utils,持续关注了解最新讲解!

原文地址:https://blog.51cto.com/13007966/2467532

时间: 2024-08-30 17:10:27

Spring中你不得不知的各种Utils的相关文章

Spring中你可能不知道的事(二)

在上一节中,我介绍了Spring中极为重要的BeanPostProcessor BeanFactoryPostProcessor Import ImportSelector,还介绍了一些其他的零碎知识点,正如我上一节所说的,Spring实在是太庞大了,是众多Java开发大神的结晶,很多功能,很多细节,可能一辈子都不会用到,不会发现,作为普通开发的我们,只能尽力去学习,去挖掘,也许哪天可以用到呢. 让我们进入正题吧. Full Lite 在上一节中的第一块内容,我们知道了Spring中除了可以注册

Spring中Utils的使用系列(一):StringUtils

在Spring中,有非常多Utils工具类,这些工具类有的是为了开发者使用的,有的只是提供给Spring框架使用的.了解这些工具类,在适当的时候使用这些工具类,对我们平时的开发还是很有帮助的,能极大方便我们的开发. Spring的工具类都是以Utils结尾,所以要查看这些工具类,只需要在API文档中查询所有*Utils即可,可以看到有多达几十个.在后面的几篇文章中我会选择几个常用的Utils,给大家展示一下Spring中的工具类的有用和常用方法. 原文地址 更多详细内容请阅读原文! Boolea

带你了解Spring中的各种Utils

在Spring中,有非常多Utils工具类,这些工具类有的是为了开发者使用的,有的只是提供给Spring框架使用的.了解这些工具类,在适当的时候使用这些工具类,对我们平时的开发还是很有帮助的,能极大方便我们的开发. 前言 Spring的工具类都是以Utils结尾,所以要查看这些工具类,只需要在API文档中查询所有*Utils即可,可以看到有多达几十个.其中有我们非常熟悉的org.springframework.util.StringUtils,有用到过的org.springframework.a

Spring中的AOP(五)——在Advice方法中获取目标方法的参数

摘要: 本文介绍使用Spring AOP编程中,在增强处理方法中获取目标方法的参数,定义切点表达式时使用args来快速获取目标方法的参数. 获取目标方法的信息 访问目标方法最简单的做法是定义增强处理方法时,将第一个参数定义为JoinPoint类型,当该增强处理方法被调用时,该JoinPoint参数就代表了织入增强处理的连接点.JoinPoint里包含了如下几个常用的方法: Object[] getArgs:返回目标方法的参数 Signature getSignature:返回目标方法的签名 Ob

spring中的AOP 以及各种通知

理解了前面动态代理对象的原理之后,其实还是有很多不足之处,因为如果在项目中有20多个类,每个类有100多个方法都需要判断是不是要开事务,那么方法调用那里会相当麻烦. spring中的AOP很好地解决了这个问题,通过 execution表达式 指定哪些包中的那些类 哪些方法 用到事务 execution(public * *(..))  所有的公共方法 execution(* set*(..))  以set开头的任意方法 execution(* com.xyz.service.AccountSer

spring中classpath和classpath*的配置区别

转自:http://www.micmiu.com/j2ee/spring/spring-classpath-start/ —————————————————————————————————————————— 在使用spring时,经常会看到类似 classpth:.classpath*: 这样的前缀,不管是加载spring xml配置文件还是其配置文件中加载资源文件都会看到这两种前缀配置,其实这两种前缀是有区别的,下面将举例详细解释. [一].测试项目准备 我们以spring中加载propert

IoC 依赖注入、以及在Spring中的实现

资源来自网络: 去年火得不行的Spring框架,一般的书籍都会从IoC和AOP开始介绍起,这个IoC概念,个人感觉资料里都写得让人看得有些痛苦,所谓IoC,就是控制反转(Inversion of Control)的缩写,这个大家都知道,但是个人觉得理解这个概念,最好应该从依赖(dependence)开始讲起,以下观点由此展开: UML中依赖关系如A依赖于B,就是A中有对方的引用;也就是说依赖就是引用:A依赖于B,就是A使用B来做事情. 所谓依赖,举个例子说明,一个类Person,另一个类Car,

【j2ee spring】15、spring中的一些概念

依赖注入 这么来说吧,在一个动作或者事件中,比如说,你现在想写字(Action),那么你需要笔,于是乎,你new了一个笔来写字,这里,你用了new笔,你这个动作和笔有了关联,没了笔,你就写不了字,也就是说,你的这个行为依赖于笔了,他们就构成了依赖关系.或者你现在想组装一台电脑(Transaction),那么你就需要显示器.主板.键鼠光驱等对象,这些对象通常是new出来的,new出来的对象和当前(this)对象就有了依赖关系. spring中对依赖的对象采用注入,这就是常说的依赖注入吧. http

spring中整合memcached,以及创建memcache的put和get方法

spring中整合memcached,以及创建memcache的put和get方法: 1:在项目中导入memcache相关的jar包 2:memcache在spring.xml的配置: 代码: 1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="