一、前言

Spring框架自带了很多很方便的工具类,我们应该学习并在日常开发中使用它,既可以提高开发效率又可以提升性能。

二、BeanUtils
  • 类路径org.springframework.beans.BeanUtils
  • 用途:提供操作JavaBean属性的便利方法,常用于复制同名属性从一个bean到另一个bean。
  • 主要方法
  • copyProperties(Object source, Object target):从源对象复制属性到目标对象,忽略不同数据类型的属性。
  • instantiateClass(Class<T> clazz):使用其无参构造器实例化一个类。

示例代码:

我们先创建两个实体类

package com.example.tcpclientdemo.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author qx
 * @date 2024/7/5
 * @des
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {

    private String name;

    private Integer age;

}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
package com.example.tcpclientdemo.dto;

import lombok.Data;

/**
 * @author qx
 * @date 2024/7/5
 * @des
 */
@Data
public class StudentDto {

    private String name;
    private Integer age;

}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.

测试copyProperties:

package com.example.tcpclientdemo;

import com.example.tcpclientdemo.bean.Student;
import com.example.tcpclientdemo.dto.StudentDto;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class TcpClientDemoApplicationTests {

    @Test
    void contextLoads() {
        //copyProperties测试
        Student student = new Student("aa", 20);
        StudentDto studentDto = new StudentDto();
        BeanUtils.copyProperties(student, studentDto);
        System.out.println(studentDto);

    }

}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.

执行结果:

StudentDto(name=aa, age=20)
  • 1.

测试instantiateClass:

package com.example.tcpclientdemo;

import com.example.tcpclientdemo.bean.Student;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class TcpClientDemoApplicationTests {

    @Test
    void contextLoads() {
        //instantiateClass
        Student student = BeanUtils.instantiateClass(Student.class);
        System.out.println(student);

    }

}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.

执行结果:

Student(name=null, age=null)
  • 1.
三、CollectionUtils
  • 类路径org.springframework.util.CollectionUtils
  • 用途:提供各种集合操作的工具方法。
  • 主要方法
  • isEmpty(Collection<?> collection):检查集合是否为空或null。
  • mergeArrayIntoCollection(Object array, Collection<Object> collection):将数组中的元素合并到集合中。
  • findValueOfType(Collection<?> collection, Class<?> type):在集合中查找指定类型的元素。

示例代码:

package com.example.tcpclientdemo;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@SpringBootTest
class TcpClientDemoApplicationTests {

    @Test
    void contextLoads() {
        //isEmpty(Collection<?> collection)
        List<String> list = new ArrayList<>();
        System.out.println(CollectionUtils.isEmpty(list));
        //mergeArrayIntoCollection(Object array, Collection<Object> collection)
        String[] array = {"a", "b", "c"};
        CollectionUtils.mergeArrayIntoCollection(array, list);
        System.out.println(list);
    }

}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.

执行结果:

true
[a, b, c]
  • 1.
  • 2.
四、StringUtils
  • 类路径:org.springframework.util.StringUtils
  • 用途:提供各种字符串处理的工具方法。
  • 主要方法
  • hasText(String str):检查字符串是否包含非空白字符。
  • commaDelimitedListToStringArray(String str):将逗号分隔的字符串转换为字符串数组。
  • split(String toSplit, String delimiter):分割字符串但不使用正则表达式。

示例代码:

package com.example.tcpclientdemo.test;

import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Set;

/**
 * @author qx
 * @date 2024/7/5
 * @des
 */
public class Demo {
    public static void main(String[] args) {
        //hasText(String str)
        boolean flag = StringUtils.hasText("aa");
        System.out.println(flag);
        //commaDelimitedListToStringArray(String str)
        Set<String> set = StringUtils.commaDelimitedListToSet("a,b,c,d");
        System.out.println(set);
        //split(String toSplit, String delimiter)
        String[] array = StringUtils.split("a,b,c,d", ",");
        System.out.println(Arrays.toString(array));
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.

执行结果:

true
[a, b, c, d]
[a, b,c,d]
  • 1.
  • 2.
  • 3.
五、ObjectUtils
  • 类路径:org.springframework.util.ObjectUtils
  • 用途:提供各种对象操作的工具方法。
  • 主要方法
  • isEmpty(Object obj):检查对象、数组是否为空或null。
  • nullSafeEquals(Object o1, Object o2):null安全的比较两个对象是否相等。

示例代码:

package com.example.tcpclientdemo.test;

import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Set;

/**
 * @author qx
 * @date 2024/7/5
 * @des
 */
public class Demo {
    public static void main(String[] args) {
        String a = null;
        //输出true
        System.out.println(ObjectUtils.isEmpty(a));
        String b = null;
        //输出true
        System.out.println(ObjectUtils.nullSafeEquals(a, b));
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.

执行结果:

true
true
  • 1.
  • 2.
六、ReflectionUtils
  • 类路径org.springframework.util.ReflectionUtils
  • 用途:提供反射相关的工具方法,简化对Java反射API的使用。
  • 主要方法
  • doWithFields(Class<?> clazz, ReflectionUtils.FieldCallback fc):对指定类的每个字段执行给定的回调。
  • findMethod(Class<?> clazz, String name, Class<?>... paramTypes):在指定类中查找方法。

示例代码:

package com.example.tcpclientdemo.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author qx
 * @date 2024/7/5
 * @des
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {

    private String name;

    private Integer age;

    public void show() {
        System.out.printf("name:%s,age:%d", name, age);
    }

}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
package com.example.tcpclientdemo.test;

import com.example.tcpclientdemo.bean.Student;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Set;

/**
 * @author qx
 * @date 2024/7/5
 * @des
 */
public class Demo {
    public static void main(String[] args) {
        Student student = new Student("aa", 20);
        //通过反射获取Student类中的show方法
        Method method = ReflectionUtils.findMethod(Student.class, "show");
        //执行show方法
        ReflectionUtils.invokeMethod(method, student);
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.

执行结果:

name:aa,age:20
  • 1.
七、ClassUtils
  • 类路径org.springframework.util.ClassUtils
  • 用途:提供与类和类加载器相关的工具方法。
  • 主要方法
  • getDefaultClassLoader():获取默认类加载器。
  • isPresent(String className, ClassLoader classLoader):检查给定名称的类是否存在。

示例代码:

package com.example.tcpclientdemo.test;

import com.example.tcpclientdemo.bean.Student;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Set;

/**
 * @author qx
 * @date 2024/7/5
 * @des
 */
public class Demo {
    public static void main(String[] args) {
        //获取默认类加载器
        ClassLoader classLoader = ClassUtils.getDefaultClassLoader();
        //检查给定名称的类是否存在。
        boolean flag = ClassUtils.isPresent("com.example.tcpclientdemo.bean.Student", classLoader);
        System.out.println(flag);
        boolean flag1 = ClassUtils.isPresent("com.example.tcpclientdemo.bean.Person", classLoader);
        System.out.println(flag1);
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.

执行结果:

true
false
  • 1.
  • 2.
八、AopUtils
  • 类路径org.springframework.aop.support.AopUtils
  • 用途:提供与面向切面编程相关的工具方法。
  • 主要方法
  • isAopProxy(Object obj):检查给定对象是否为AOP代理。
  • getTargetClass(Object candidate):获取代理对象背后的目标类。
九、PropertyAccessorUtils
  • 类路径org.springframework.beans.PropertyAccessorUtils
  • 用途:提供属性访问器相关的工具方法。
  • 主要方法
  • getPropertyAccessorName(String propertyName):从复合属性名中获取最终的属性访问器名。
十、FileCopyUtils
  • 类路径org.springframework.util.FileCopyUtils
  • 用途:提供文件复制相关的工具方法。
  • 主要方法
  • copy(byte[] in, OutputStream out):将字节数组复制到输出流。
  • copy(File in, File out):将一个文件内容复制到另一个文件。

示例代码:

package com.example.tcpclientdemo.test;

import com.example.tcpclientdemo.bean.Student;
import org.springframework.aop.support.AopUtils;
import org.springframework.util.*;

import java.io.*;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Set;

/**
 * @author qx
 * @date 2024/7/5
 * @des
 */
public class Demo {
    public static void main(String[] args) throws IOException {
        String str = "hello,world";
        byte[] bytes = str.getBytes();
        //文件保存的路径
        File file = new File("E:" + File.separator + "test" + File.separator + "demo.txt");
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdir();
        }
        OutputStream outputStream = Files.newOutputStream(file.toPath());
        FileCopyUtils.copy(bytes, outputStream);
        outputStream.close();
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.

执行结果:

别重复造轮子,Spring工具类带你飞_工具

别重复造轮子,Spring工具类带你飞_BeanUtils_02

十一、ResourceUtils
  • 类路径org.springframework.util.ResourceUtils
  • 用途:识别资源加载的工具类,帮助加载类路径或者文件系统内的资源文件。
  • 主要方法
  • getFile(String resourceLocation):根据资源路径获取文件。
  • getURL(String resourceLocation):根据资源路径获取URL。

示例代码:

package com.example.tcpclientdemo.test;

import org.springframework.util.*;

import java.io.*;
import java.net.URL;

/**
 * @author qx
 * @date 2024/7/5
 * @des
 */
public class Demo {
    public static void main(String[] args) throws IOException {
        String filePath = "E:" + File.separator + "test" + File.separator + "demo.txt";
        File file = ResourceUtils.getFile(filePath);
        System.out.println(file.getAbsolutePath());
        URL url = ResourceUtils.getURL(filePath);
        System.out.println(url);
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.

执行结果:

E:\test\demo.txt
file:/E:/test/demo.txt
  • 1.
  • 2.
十二、TransactionSynchronizationManager
  • 类路径org.springframework.transaction.support.TransactionSynchronizationManager
  • 用途:用于事务同步,管理资源和事务同步相关的回调。
  • 主要方法
  • bindResource(Object key, Object value):绑定资源到当前事务。
  • getResource(Object key):获取绑定到当前事务的资源。
十三、WebUtils
  • 类路径org.springframework.web.util.WebUtils
  • 用途:为Web应用程序提供工具方法。
  • 主要方法
  • getRealPath(ServletContext servletContext, String path):获取相对于Web应用根目录的真实路径。
  • findParameterValue(Map<String, ?> params, String paramName):在参数Map中查找指定的参数值。

示例代码:

package com.example.tcpclientdemo.controller;

import com.example.tcpclientdemo.service.IndexService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.WebUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.CompletableFuture;

/**
 * @author qx
 * @date 2024/7/4
 * @des
 */
@Slf4j
@RestController
public class IndexController {


    @GetMapping("/index")
    public String testIndex(HttpServletRequest request) throws FileNotFoundException {
        ServletContext servletContext = request.getServletContext();
        String path = WebUtils.getRealPath(servletContext, "TestController");
        log.info("path:{}", path);
        return "index success";
    }

}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.

执行结果:

2024-07-05 10:33:02.805  INFO 2084 --- [nio-8080-exec-2] c.e.t.controller.IndexController         : path:C:\Users\qx\AppData\Local\Temp\tomcat-docbase.8080.7796970697002068219\TestController
  • 1.

这些工具类在Spring应用开发中起到关键的辅助作用,减少了代码的重复编写,提高了开发效率。需要注意的是,不同版本的Spring可能在这些工具类的API上有所变动,因此在使用时应查阅对应版本的Spring文档。