365bet手机在线网页-bt365娱乐官网-365手机版

bt365娱乐官网

spring boot 工具类(0-10)

spring boot 工具类(0-10)

-------------------------------------------------------------------------------

1、spring 24 工具类

Spring 框架如同一个 “瑞士军刀” 工具箱,内置了众多实用工具类,覆盖对象操作、集合处理、反射、IO、Web 等多个场景。以下精选 24 个最常用的 “瑞士军刀” 工具类,附带核心功能和实战示例,帮你提升开发效率。

一、核心容器工具类(Core Container)

org.springframework.beans.BeanUtils

功能:对象属性拷贝、类信息操作。

场景:DTO 与实体类转换。

java

运行

// 拷贝属性(忽略null值)

BeanUtils.copyProperties(source, target, getNullPropertyNames(source));

org.springframework.beans.PropertyAccessorFactory

功能:创建属性访问器,动态读写对象属性。

java

运行

PropertyAccessor accessor = PropertyAccessorFactory.forBeanPropertyAccess(user);

accessor.setPropertyValue("username", "newName"); // 动态设值

org.springframework.core.io.Resource

功能:统一资源访问(文件、类路径、URL 等)。

java

运行

Resource resource = new ClassPathResource("config.properties");

InputStream is = resource.getInputStream(); // 读取类路径资源

org.springframework.core.io.support.ResourcePatternResolver

功能:批量匹配资源(如通配符匹配)。

java

运行

Resource[] resources = new PathMatchingResourcePatternResolver()

.getResources("classpath:*.xml"); // 加载所有XML资源

二、工具类(Utils)

org.springframework.util.StringUtils

功能:字符串空判断、分割、拼接等。

java

运行

boolean hasText = StringUtils.hasText(str); // 非空且非空白

String[] parts = StringUtils.split(str, ","); // 分割字符串

org.springframework.util.CollectionUtils

功能:集合空判断、交集 / 并集运算。

java

运行

boolean isEmpty = CollectionUtils.isEmpty(list); // 安全判断空集合

List union = CollectionUtils.union(list1, list2); // 并集

org.springframework.util.ObjectUtils

功能:对象空判断、数组操作。

java

运行

boolean isNull = ObjectUtils.isEmpty(obj); // 支持数组/集合空判断

String str = ObjectUtils.nullSafeToString(obj); // 避免NPE的toString

org.springframework.util.ReflectionUtils

功能:简化反射操作(方法 / 字段访问)。

java

运行

// 查找并调用方法

Method method = ReflectionUtils.findMethod(User.class, "getId");

Object result = ReflectionUtils.invokeMethod(method, user);

org.springframework.util.AntPathMatcher

功能:Ant 风格路径匹配(如 URL 路由)。

java

运行

boolean match = new AntPathMatcher().match("/user/*", "/user/123"); // true

org.springframework.util.DigestUtils

功能:MD5、SHA 等哈希计算。

java

运行

String md5 = DigestUtils.md5DigestAsHex("password".getBytes());

三、Web 相关工具类

org.springframework.web.util.UriComponentsBuilder

功能:构建和解析 URL。

java

运行

URI uri = UriComponentsBuilder.fromPath("/user")

.queryParam("id", 1)

.build()

.toUri(); // 生成 /user?id=1

org.springframework.web.util.HtmlUtils

功能:HTML 转义 / 反转义(防 XSS)。

java

运行

String escaped = HtmlUtils.htmlEscape("