Spring常用一些工具类实例汇总

一、内置Resource类型

  • org.springframework.core.io.UrlResource
  • org.springframework.core.io.ClassPathResource:以类路径的方式进行访问
  • org.springframework.core.io.FileSystemResource:以文件系统绝对路径的方式进行访问
  • org.springframework.web.context.support.ServletContextResource:以相对于 Web 应用根目录的方式进行访问
  • org.springframework.core.io.InputStreamResource
  • org.springframework.core.io.ByteArrayResource
  • org.springframework.core.io.support.EncodedResource :就是Resource加上encoding, 可以认为是有编码的资源。当您使用 Resource 实现类加载文件资源时,它默认采用操作系统的编码格式。如果文件资源采用了特殊的编码格式(如 UTF-8),则在读取资源内容时必须事先通过 EncodedResource 指定编码格式,否则将会产生中文乱码的问题。
  • org.springframework.core.io.VfsResource:在jboss里经常用到, 相应还有 工具类 VfsUtils
  • org.springframework.util.ResourceUtils:它支持“classpath:”和“file:”的地址前缀,它能够从指定的地址加载文件资源,常用方法:getFile()

二、本地化文件资源

org.springframework.core.io.support.LocalizedResourceHelper:允许通过文件资源基名和本地化实体获取匹配的本地化文件资源并以 Resource 对象返回

三、操作 Servlet API 的工具类

org.springframework.web.context.support.WebApplicationContextUtils 工具类获取 WebApplicationContext 对象。

WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);

四、XML工具类

  • org.springframework.util.xml.AbstractStaxContentHandler
  • org.springframework.util.xml.AbstractStaxXMLReader
  • org.springframework.util.xml.AbstractXMLReader
  • org.springframework.util.xml.AbstractXMLStreamReader
  • org.springframework.util.xml.DomUtils
  • org.springframework.util.xml.SimpleNamespaceContext
  • org.springframework.util.xml.SimpleSaxErrorHandler
  • org.springframework.util.xml.SimpleTransformErrorListener
  • org.springframework.util.xml.StaxUtils
  • org.springframework.util.xml.TransformerUtils

五、web相关工具类

  • org.springframework.web.util.CookieGenerator
  • org.springframework.web.util.HtmlCharacterEntityDecoder
  • org.springframework.web.util.HtmlCharacterEntityReferences
  • org.springframework.web.util.HtmlUtils:HTML 特殊字符转义,常用方法 htmlEscape(),htmlUnescape()。
  • org.springframework.web.util.HttpUrlTemplate 这个类用于用字符串模板构建url, 它会自动处理url里的汉字及其它相关的编码. 在读取别人提供的url资源时, 应该经常用 String url = "http://localhost/myapp/{name}/{id}"
  • org.springframework.web.util.JavaScriptUtils:JavaScript 特殊字符转义,常用方法:javaScriptEscape()。
  • org.springframework.web.util.Log4jConfigListener 用listener的方式来配制log4j在web环境下的初始化
  • org.springframework.web.util.UriTemplate
  • org.springframework.web.util.UriUtils :处理uri里特殊字符的编码
  • org.springframework.web.util.WebUtils
  • getCookie(HttpServletRequest request, String name) 获取 HttpServletRequest 中特定名字的 Cookie 对象。如果您需要创建 Cookie, Spring 也提供了一个方便的 CookieGenerator 工具类。
  • getSessionAttribute(HttpServletRequest request, String name) 获取 HttpSession 特定属性名的对象,否则您必须通过 request.getHttpSession.getAttribute(name) 完成相同的操作。
  • getRequiredSessionAttribute(HttpServletRequest request, String name) 和上一个方法类似,只不过强制要求 HttpSession 中拥有指定的属性,否则抛出异常。
  • getSessionId(HttpServletRequest request) 获取 Session ID 的值。
  • void exposeRequestAttributes(ServletRequest request, Map attributes) 将 Map 元素添加到 ServletRequest 的属性列表中,当请求被导向(forward)到下一个处理程序时,这些请求属性就可以被访问到了。

六、参数检测工具类org.springframework.util.Assert

Assert断言工具类,通常用于数据合法性检查。

平时做判断通常都是这样写:

if (message== null || message.equls("")) {
throw new IllegalArgumentException("输入信息错误!");
}

用Assert工具类上面的代码可以简化为:

Assert.hasText((message, "输入信息错误!");
下面来介绍一下Assert 类中的常用断言方法:

  • Assert.notNull(Object object, "object is required") - 对象非空
  • Assert.isTrue(Object object, "object must be true") - 对象必须为true
  • Assert.notEmpty(Collection collection, "collection must not be empty") - 集合非空
  • Assert.hasLength(String text, "text must be specified") - 字符不为null且字符长度不为0
  • Assert.hasText(String text, "text must not be empty") - text 不为null且必须至少包含一个非空格的字符
  • Assert.isInstanceOf(Class clazz, Object obj, "clazz must be of type [clazz]") - obj必须能被正确造型成为clazz 指定的类

七、请求工具类 org.springframework.web.bind.ServletRequestUtils

//取请求参数的整数值:
public static Integer getIntParameter(ServletRequest request, String name)
public static int getIntParameter(ServletRequest request, String name, int defaultVal) -->单个值
public static int[] getIntParameters(ServletRequest request, String name) -->数组

还有譬如long、float、double、boolean、String的相关处理方法。

八、其他工具类

  • org.springframework.util.FileCopyUtils:它提供了许多一步式的静态操作方法,能够将文件内容拷贝到一个目标 byte[]、String 甚至一个输出流或输出文件中。
  • org.springframework.core.io.support.PropertiesLoaderUtils:允许您直接通过基于类路径的文件地址加载属性资源。
  • oorg.springframework.orm.hibernate5.support.OpenSessionInViewFilter:过滤器将 Hibernate Session 绑定到请求线程中,它将自动被 Spring 的事务管理器探测到。所以 OpenSessionInViewFilter 适用于 Service 层使用 HibernateTransactionManager 或 JtaTransactionManager 进行事务管理的环境,也可以用于非事务只读的数据操作中。
  • org.springframework.web.filter.CharacterEncodingFilter:当通过表单向服务器提交数据时,一个经典的问题就是中文乱码问题。虽然我们所有的 JSP 文件和页面编码格式都采用 UTF-8,但这个问题还是会出现。解决的办法很简单,我们只需要在 web.xml 中配置一个 Spring 的编码转换过滤器就可以了。
  • org.springframework.web.filter.ServletContextRequestLoggingFilter:请求跟踪日志过滤器。在日志级别为 DEBUG 时才会起作用。
  • org.springframework.web.util.WebAppRootListener
  • org.springframework.web.IntrospectorCleanupListener:缓存清除监听器
  • org.springframework.util.StringUtils:字符串工具类
  • CollectionUtils:集合工具类
  • org.springframework.util.SerializationUtils:对象序列化与反序列化
  • org.springframework.util.NumberUtils:处理数字的工具类, 有parseNumber 可以把字符串处理成我们指定的数字格式, 还支持format格式, convertNumberToTargetClass 可以实现Number类型的转化。
  • org.springframework.util.FileSystemUtils:递归复制、删除一个目录。
  • org.springframework.util.DigestUtils:MD5加密
  • org.springframework.util.AntPathMatcher:风格的处理
  • org.springframework.util.AntPathStringMatcher
  • org.springframework.util.ClassUtils:用于Class的处理
  • org.springframework.util.CommonsLogWriter
  • org.springframework.util.CompositeIterator
  • org.springframework.util.ConcurrencyThrottleSupport
  • org.springframework.util.CustomizableThreadCreator
  • org.springframework.util.DefaultPropertiesPersister
  • org.springframework.util.LinkedCaseInsensitiveMap:key值不区分大小写的LinkedMap
  • org.springframework.util.LinkedMultiValueMap:一个key可以存放多个值的LinkedMap
  • org.springframework.util.ObjectUtils:有很多处理null object的方法. 如nullSafeHashCode, nullSafeEquals, isArray, containsElement, addObjectToArray, 等有用的方法
  • org.springframework.util.PatternMatchUtils:spring里用于处理简单的匹配。
  • org.springframework.util.PropertyPlaceholderHelper:用于处理占位符的替换。
  • org.springframework.util.ReflectionUtils:反射常用工具方法. 有 findField, setField, getField, findMethod, invokeMethod等有用的方法。
  • org.springframework.util.StopWatch 一个很好的用于记录执行时间的工具类, 且可以用于任务分阶段的测试时间. 最后支持一个很好看的打印格式. 这个类应该经常用。
  • org.springframework.util.SystemPropertyUtils
  • org.springframework.util.TypeUtils:用于类型相容的判断. isAssignable
  • org.springframework.util.WeakReferenceMonitor 弱引用的监控

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Spring框架JavaMailSender发送邮件工具类详解

    本文实例为大家分享了Spring框架JavaMailSender发送邮件工具类,供大家参考,具体内容如下 需要用到的jar包: 下面是发送工具类代码: package com.test.email; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.Jav

  • 浅谈HBase在SpringBoot项目里的应用(含HBaseUtil工具类)

    背景: 项目这两个月开始使用HBase来读写数据,网上现成的HBase工具类要么版本混杂,要么只是Demo级别的简单实现,各方面都不完善: 而且我发现HBase查询有很多种方式,首先大方向上有 Get 和 Scan两种,其次行键.列族.列名(限定符).列值(value).时间戳版本等多种组合条件,还有各种过滤器的选择,协处理器的应用,所以必须根据自己项目需求和HBase行列设计来自定义HBase工具类和实现类! 经过我自己的研究整理,在此分享下初步的实现方案吧 ~ 注:HBase版本:1.3.0

  • Spring Boot中优雅的获取yml文件工具类

    如何在spring boot中优雅的获取.yml文件工具类呢 代码如下: package com.common.base.utils.base; import com.common.base.generator.ResourceManager; import org.yaml.snakeyaml.Yaml; import java.io.InputStream; import java.util.HashMap; import java.util.Map; /** * yml文件工具类 */ p

  • Spring boot工具类静态属性注入及多环境配置详解

    由于需要访问MongoDB,但是本地开发环境不能直接连接MongoDB,需要通过SecureCRT使用127.0.0.2本地IP代理.但是程序部署到线上生产环境后,是可以直接访问MongoDB的,因此开发好程序后,总是要修改一下MongoDB服务器的IP才能提交代码,这样很是不方便. private static final String PUBCHAT_HOST = "127.0.0.2"; // private static final String PUBCHAT_HOST =

  • 兼容Spring Boot 1.x和2.x配置类参数绑定的工具类SpringBootBindUtil

    为了让我提供的通用 Mapper 的 boot-starter 同时兼容 Spring Boot 1.x 和 2.x,增加了这么一个工具类. 在 Spring Boot 中,能够直接注入 XXProperties 类的地方不需要使用这个工具类. 但是在Spring 的接口和启动流程设计中,有些情况下只能通过EnvironmentAware接口得到Environment对象,此时你想得到 XXProperties 类没有更好的办法. 也许有人直接从Environment 对象中遍历获取所有的配置信

  • spring boot结合Redis实现工具类的方法示例

    自己整理了 spring boot 结合 Redis 的工具类 引入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> 加入配置 # Redis数据库索引(默认为0) spring.redis.database=0 # Redis

  • Spring获取ApplicationContext对象工具类的实现方法

     Spring获取ApplicationContext对象工具类的实现方法 (1)实现的工具类: package com.util; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; final public class ApplicationContextUtil { private s

  • Springboot实现多线程注入bean的工具类操作

    场景: 使用springboot多线程,线程类无法自动注入需要的bean 解决方法: 通过工具类获取需要的bean 工具类代码: import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springfram

  • Spring常用一些工具类实例汇总

    一.内置Resource类型 org.springframework.core.io.UrlResource org.springframework.core.io.ClassPathResource:以类路径的方式进行访问 org.springframework.core.io.FileSystemResource:以文件系统绝对路径的方式进行访问 org.springframework.web.context.support.ServletContextResource:以相对于 Web 应

  • Android常用正则表达式验证工具类(实例代码)

    东西不多,但一般项目够用了. public class RegularUtil { //身份证 public static final String REGEX_ID_CARD = "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$"; //验证邮箱 public static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\

  • Android快速开发系列 10个常用工具类实例代码详解

    打开大家手上的项目,基本都会有一大批的辅助类,今天特此整理出10个基本每个项目中都会使用的工具类,用于快速开发~~在此感谢群里给我发项目中工具类的兄弟/姐妹~ 1.日志工具类L.java package com.zhy.utils; import android.util.Log; /** * Log统一管理类 * * * */ public class L { private L() { /* cannot be instantiated */ throw new UnsupportedOpe

  • Android编程实现的身份证、车牌号正则验证工具类实例

    本文实例讲述了Android编程实现的身份证.车牌号正则验证工具类.分享给大家供大家参考,具体如下: /** * 正则表达式验证工具类(验证身份证.车牌号等) * * @author chenlin * */ public class ValidateUtil { /** * 验证str是否为正确的身份证格式 * * @param str * @return */ public static boolean isIdentityCard(EditText view) { boolean flag

  • Android开发中4个常用的工具类【Toast、SharedPreferences、网络及屏幕操作】

    本文实例讲述了Android开发中4个常用的工具类.分享给大家供大家参考,具体如下: 1.土司工具类(Toast管理) /** * Toast统一管理类 * * @Project App_ZXing * @Package com.android.scan * @author chenlin * @version 1.0 * @Date 2013年7月6日 * @Note TODO */ public class ToastUtil { private ToastUtil() { /* canno

  • 详解Spring中BeanUtils工具类的使用

    目录 简介 Spring的BeanUtils方法 Spring的BeanUtils与Apache的BeanUtils区别 实例 简介 说明 本文介绍Spring的BeanUtils工具类的用法. 我们经常需要将不同的两个对象实例进行属性复制,比如将DO对象进行属性复制到DTO,这种转换最原始的方式就是手动编写大量的 get/set代码,很繁琐.为了解决这一痛点,就诞生了一些方便的类库,常用的有 Apache的 BeanUtils,Spring的 BeanUtils, Dozer,Orika等拷贝

  • java Arrays工具类实例详解

    Arrays工具类属于java中常用的工具类 public static void sort(int[] a) public static void sort(int[] a,int fromIndex, int toIndex) public static void sort(long[] a) public static void sort(long[] a,int fromIndex, int toIndex) public static void sort(short[] a) publ

  • HttpUtils 发送http请求工具类(实例讲解)

    废话不多说,直接上代码 import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFac

  • Java语言Lang包下常用的工具类介绍

    无论你在开发哪中 Java 应用程序,都免不了要写很多工具类/工具函数.你可知道,有很多现成的工具类可用,并且代码质量都很不错,不用你写,不用你调试,只要你发现. 在 Apache Jakarta Common 中, Lang 这个 Java 工具包是所有 Apache Jakarta Common 项目中被使用最广泛的,几乎你所知道的名气比较大的软件里面都有用到它,包括 Tomcat, Weblogic, Websphere, Eclipse 等等.我们就从这个包开始介绍整个 common 项

  • Java语言描述MD5加密工具类实例代码

    编程中经常有用到MD5加密的情况,Java语言并没有像PHP一样提供原生的MD5加密字符串的函数,需要MD5加密的时候,往往需要自己写. 代码如下: import java.security.MessageDigest; public class MD5 { //公盐 private static final String PUBLIC_SALT = "demo" ; //十六进制下数字到字符的映射数组 private final static String[] hexDigits =

随机推荐