Spring 常用工具类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring 常用工具类相关的知识,希望对你有一定的参考价值。

参考技术A StringUtils:(Spring 4.0+工具类)

public static boolean hasLength(CharSequence str)

public static boolean isEmpty(Object str)

public static boolean hasText(String str)

public static String replace(String inString, String oldPattern, String newPattern)

public static String delete(String inString, String pattern)

public static String capitalize(String str) //首字母大写

public static String uncapitalize(String str)  //首字母小写

public static String getFilename(String path) //文件路径截取文件名

public static String getFilenameExtension(String path)  //文件路径截取后缀

ClassUtils:(Spring 4.0+工具类)

public static Class forName(String name, ClassLoader classLoader) throws ClassNotFoundException, LinkageError

public static boolean isPresent(String className, ClassLoader classLoader)

public static Class getUserClass(Class clazz)  //CGLIB代理类获取父类

public static String getShortName(String className)

public static String getShortNameAsProperty(Class clazz)  //获取类名且首字母变小写

public static Method getMostSpecificMethod(Method method, Class targetClass)  //如果这个方法是接口的方法,则获取实现类中实现的方法

ObjectUtils:

BeanUtils:(Spring 4.0+工具类)

public static T instantiate(Class clazz) throws BeanInstantiationException

public static PropertyDescriptor[] getPropertyDescriptors(Class clazz) throws BeansException

public static PropertyDescriptor getPropertyDescriptor(Class clazz, String propertyName) throws BeansException

public static PropertyDescriptor findPropertyForMethod(Method method) throws BeansException

public static PropertyDescriptor findPropertyForMethod(Method method, Class clazz) throws BeansException

public static Class findPropertyType(String propertyName, Class... beanClasses)

public static boolean isSimpleProperty(Class clazz)

public static boolean isSimpleValueType(Class clazz)

public static void copyProperties(Object source, Object target)

public static void copyProperties(Object source, Object target, String... ignoreProperties) throws BeansException

AnnotatedElementUtils,

AnnotationUtils:(Spring 4.0+工具类)

public static Map getAnnotationAttributes(Annotation annotation)

public static Object getValue(Annotation annotation)  //获取注解上的value()值

public static Object getValue(Annotation annotation, String attributeName)

public static Object getDefaultValue(Annotation annotation)

public static Object getDefaultValue(Annotation annotation, String attributeName)  //获取注解上的属性默认值

AnnotationAttributes: (Spring 4.0+工具类)

public AnnotationAttributes(Class annotationType)

public AnnotationAttributes(Map map)

public Class annotationType()

public String getString(String attributeName)

public String[] getStringArray(String attributeName)

public boolean getBoolean(String attributeName)

public N getNumber(String attributeName)

public Class getClass(String attributeName)

public AnnotationAttributes getAnnotation(String attributeName)

BeanWrapperImpl: (Spring 4.0+工具类)

public BeanWrapperImpl(Object object)

public BeanWrapperImpl(Class clazz)

public final Object getWrappedInstance()

public final Class getWrappedClass()

public void setPropertyValue(String propertyName, Object value) throws BeansException

public Class getPropertyType(String propertyName) throws BeansException

public Object getPropertyValue(String propertyName)

public void setAutoGrowNestedPaths(boolean autoGrowNestedPaths) //是否自动创建属性实例

public void setPropertyValues(Map map) throws BeansException

FileUtils:

public static File getFile(File directory, String... names)

public static Collection listFiles( File directory, IOFileFilter fileFilter, IOFileFilter dirFilter)  //获取目录下的文件

public static Iterator iterateFiles(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter)  //遍历目录下的文件

public static Collection listFiles(File directory, String[] extensions, boolean recursive)  //获取目录下的文件,可指定是否递归

public static void copyFileToDirectory(File srcFile, File destDir) throws IOException  //拷贝文件到指定目录

public static void copyFile(File srcFile, File destFile) throws IOException

public static long copyFile(File input, OutputStream output)

public static void copyInputStreamToFile(InputStream source, File destination)

public static void deleteDirectory(File directory)   //删除目录

public static void cleanDirectory(File directory)  //清空目录下文件

public static String readFileToString(File file)

public static byte[] readFileToByteArray(File file)

public static List readLines(File file)

public static void writeStringToFile(File file, String data) throws IOException   //将String覆盖File内的内容

public static void writeStringToFile(File file, String data, String encoding, boolean append)   //将String追加到File内

public static void writeLines(File file, String encoding, Collection lines) throws IOException

public static void writeLines(File file, String encoding, Collection lines, boolean append)

public static void writeLines(File file, Collection lines) throws IOException

IOUtils:

public static byte[] toByteArray(InputStream input) throws IOException

public static byte[] toByteArray(Reader input) throws IOException

public static char[] toCharArray(InputStream is) throws IOException

public static String toString(InputStream input) throws IOException

public static String toString(Reader input) throws IOException

public static List readLines(InputStream input) throws IOException

public static List readLines(Reader input) throws IOException

public static InputStream toInputStream(String input)

public static void write(byte[] data, OutputStream output)

public static void write(String data, OutputStream output) throws IOException

public static void writeLines(Collection lines, String lineEnding, OutputStream output) throws IOException

public static int copy(InputStream input, OutputStream output)

public static int copy(Reader input, Writer output) throws IOException

public static int read(InputStream input, byte[] buffer) throws IOException

public static int read(Reader input, char[] buffer) throws IOException

Character:

public static boolean isLowerCase(char ch)

public static boolean isUpperCase(char ch)

public static boolean isDigit(char ch)

ReflectionUtils:(Spring 4.0+工具类)

public static void doWithLocalMethods(Class clazz, MethodCallback mc)

public static void doWithMethods(Class clazz, MethodCallback mc)

public static void doWithMethods(Class clazz, MethodCallback mc, MethodFilter mf)

public static void doWithLocalFields(Class clazz, FieldCallback fc)

public static void doWithFields(Class clazz, FieldCallback fc)

public static void doWithFields(Class clazz, FieldCallback fc, FieldFilter ff)

ResolvableType:(Spring 4.0+工具类)

public static ResolvableType forClass(Class clazz)

public static ResolvableType forInstance(Object instance)

public static ResolvableType forField(Field field)

public static ResolvableType forConstructorParameter(Constructor constructor, int parameterIndex)

public static ResolvableType forMethodReturnType(Method method)

public static ResolvableType forMethodParameter(Method method, int parameterIndex)

public ResolvableType asMap()

public ResolvableType asCollection()

public ResolvableType as(Class type)

public ResolvableType getGeneric(int... indexes)   //Map> getGeneric(0) = Integer, getGeneric(1, 0) = String

public Class resolveGeneric(int... indexes)

public Class resolve()

Assert: (Spring 4.0+工具类)

public static void state(boolean expression, String message)

public static void isTrue(boolean expression, String message)

public static void isNull(Object object, String message)

public static void notNull(Object object, String message)

public static void hasText(String text, String message)

public static void notEmpty(Object[] array, String message)

public static void notEmpty(Collection collection, String message)

public static void notEmpty(Map map, String message)

public static void isInstanceOf(Class type, Object obj, String message)

public static void isAssignable(Class superType, Class subType, String message)

Arrays:

public static void sort(T[] a, Comparator c)

public static void fill(Object[] a, Object val)

public static List asList(T... a)

public static T[] copyOf(T[] original, int newLength)

Collections:

public static void sort(List list, Comparator c)

public static void fill(List list, T obj)

public static void copy(List dest, List src)

public static Collection unmodifiableCollection(Collection c)

public static List unmodifiableList(List list)

public static Map unmodifiableMap(Map m)

public static List singletonList(T o)

public static boolean addAll(Collection c, T... elements)

CollectionUtils (Spring 4.0+工具类)

public static boolean isEmpty(Collection collection)

public static boolean isEmpty(Map map)

public static boolean containsInstance(Collection collection, Object element)

MethodIntrospector: (Spring 4.0+工具类)

public static Map selectMethods(Class targetType, final MetadataLookup metadataLookup)

public static Set selectMethods(Class targetType, final ReflectionUtils.MethodFilter methodFilter)

public static Method selectInvocableMethod(Method method, Class targetType)

PropertyDescriptor: (Spring 4.0+工具类)

public PropertyDescriptor(String propertyName, Class beanClass) throws IntrospectionException

public synchronized Class getPropertyType()

public synchronized Method getReadMethod()

public synchronized Method getWriteMethod()

Spring工具类之PropertiesLoaderUtils

工具从古至今都是为了方便人们生活和工作的利器,在程序语言中也不例外,Spring具有很多工具类,有的是专属框架工具类,而有的是开放给开发者使用的工具类,那么我们今天要讲的呢就是Spring中的utils,一起来看看吧!

前言

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=u4E2Du6587

完成代码:

@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">;

<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方法完成的。

小结
本节中,简单介绍了Spring的第一个Utils:PropertiesLoaderUtils,后面持续送上更多工具类的介绍。

以上是关于Spring 常用工具类的主要内容,如果未能解决你的问题,请参考以下文章

spring中常用工具类介绍

Spring 常用的一些工具类

Spring常用工具类

Spring常用工具类

Spring工具类之PropertiesLoaderUtils

spring工具类中注入使用bean