Boost Your Spring Boot Projects with Essential Utility Classes and Code Samples
This article categorizes Spring Boot utility classes into built‑in and third‑party groups, explains their purposes, and provides practical code examples for each, helping developers streamline code, improve efficiency, and avoid reinventing common functionality.
Introduction
When developing Spring Boot projects, various utility classes can simplify code and improve efficiency. This article categorises them into two groups: those bundled with Spring Boot and third‑party libraries that require manual dependencies, providing at least three common method examples for each.
Spring Framework Built‑in Utilities
org.springframework.util.StringUtils
StringUtils offers static methods for common string operations.
import org.springframework.util.StringUtils;
public class StringUtilsExample {
public static void main(String[] args) {
// 判断字符串是否有内容(非空且不全是空白)
boolean hasText = StringUtils.hasText("Hello, Spring!");
System.out.println("Does the string have text? " + hasText); // true
// 判断字符串是否为空(null 或长度为0)
boolean isEmpty = StringUtils.isEmpty("");
System.out.println("Is the string empty? " + isEmpty); // true
// 将数组元素连接成字符串
String[] words = {"Hello", "world"};
String joinedString = StringUtils.arrayToDelimitedString(words, " ");
System.out.println("Joined string: " + joinedString); // Hello world
}
}org.springframework.util.ReflectionUtils
ReflectionUtils provides convenient reflection methods for accessing private fields and invoking private methods.
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Field;
class Person {
private String name = "John";
public String getName() { return name; }
}
public class ReflectionUtilsExample {
public static void main(String[] args) throws IllegalAccessException {
Person person = new Person();
// 获取并设置私有字段值
Field field = ReflectionUtils.findField(Person.class, "name");
ReflectionUtils.makeAccessible(field);
field.set(person, "Jane");
System.out.println("Name after reflection modification: " + person.getName()); // Jane
// 使用反射获取字段值
Object value = ReflectionUtils.getField(field, person);
System.out.println("Value retrieved by reflection: " + value); // Jane
// 查找所有方法
ReflectionUtils.doWithMethods(Person.class, method -> System.out.println("Method found: " + method.getName()));
}
}org.springframework.util.Assert
Assert supplies assertion methods to validate program state or parameters.
import org.springframework.util.Assert;
public class AssertExample {
public static void main(String[] args) {
try {
// 校验对象是否为 null
Assert.notNull(null, "Object must not be null");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage()); // Object must not be null
}
try {
// 校验字符串是否为空
Assert.hasText("", "Text must not be empty");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage()); // Text must not be empty
}
try {
// 校验表达式是否为 true
Assert.isTrue(5 < 4, "Expression is false");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage()); // Expression is false
}
}
}org.springframework.util.ClassUtils
ClassUtils contains helper methods related to class loading, such as checking subclass relationships or class existence.
import org.springframework.util.ClassUtils;
public class ClassUtilsExample {
public static void main(String[] args) {
// 判断是否实现了接口
boolean isAssignable = ClassUtils.isAssignable(java.util.List.class, java.util.ArrayList.class);
System.out.println("Is ArrayList assignable from List? " + isAssignable); // true
// 获取简短类名
String shortClassName = ClassUtils.getShortName("java.util.ArrayList");
System.out.println("Short class name: " + shortClassName); // ArrayList
// 判断类是否存在
boolean exists = ClassUtils.isPresent("java.util.ArrayList", ClassUtilsExample.class.getClassLoader());
System.out.println("ArrayList class present? " + exists); // true
}
}org.springframework.util.ResourceUtils
ResourceUtils helps locate and load resource files, useful for reading configuration or template files.
import org.springframework.util.ResourceUtils;
import java.io.File;
import java.io.FileNotFoundException;
public class ResourceUtilsExample {
public static void main(String[] args) {
try {
// 加载classpath下的资源文件
File file = ResourceUtils.getFile("classpath:application.properties");
System.out.println("File path: " + file.getAbsolutePath());
// 加载文件系统中的文件
File systemFile = ResourceUtils.getFile("file:/path/to/your/file.txt");
System.out.println("System file path: " + systemFile.getAbsolutePath());
} catch (FileNotFoundException e) {
System.err.println("File not found: " + e.getMessage());
}
}
}Third‑Party Utility Libraries (Manual Dependency)
Apache Commons Lang3 (commons‑lang3)
Provides rich utilities for strings, objects, and arrays.
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
public class CommonsLang3Example {
public static void main(String[] args) {
// 判断字符串是否为空
System.out.println(StringUtils.isEmpty(null)); // true
System.out.println(StringUtils.isEmpty("")); // true
System.out.println(StringUtils.isEmpty("abc")); // false
// 随机生成6位字符串
System.out.println(StringUtils.randomAlphanumeric(6)); // e.g., 7xK9mL
// 合并两个数组
int[] arr1 = {1, 2, 3};
int[] arr2 = {4, 5};
int[] merged = ArrayUtils.addAll(arr1, arr2);
for (int i : merged) {
System.out.print(i + " "); // 1 2 3 4 5
}
}
}Google Guava (guava)
Offers functional programming support, collection enhancements, Optional, and preconditions.
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.base.Optional;
public class GuavaExample {
public static void main(String[] args) {
// 参数检查
try {
Preconditions.checkNotNull(null, "Value can't be null");
} catch (Exception e) {
System.out.println(e.getMessage()); // Value can't be null
}
// 创建不可变列表
List<String> list = Lists.newArrayList("Java", "Python", "Go");
System.out.println(list); // [Java, Python, Go]
// 使用 Optional 处理可能为 null 的值
Optional<String> optional = Optional.fromNullable(null);
System.out.println(optional.or("default")); // default
}
}Hutool (hutool‑all)
A comprehensive Chinese Java utility library covering most daily needs.
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
public class HutoolExample {
public static void main(String[] args) {
// 判断字符串是否为空
System.out.println(StrUtil.isEmpty("")); // true
System.out.println(StrUtil.isEmpty("hello")); // false
// 生成随机数字
System.out.println(RandomUtil.randomNumbers(6)); // e.g., 832917
// 发送 HTTP GET 请求
String result = HttpUtil.get("https://jsonplaceholder.typicode.com/posts/1");
System.out.println(result); // JSON response
}
}Lombok (lombok)
Generates boilerplate code at compile time, reducing manual getters/setters, constructors, etc.
import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
class User {
private String name;
private int age;
}
public class LombokExample {
public static void main(String[] args) {
User user = new User("Tom", 25);
System.out.println(user.toString()); // User(name=Tom, age=25)
}
}Jackson (jackson‑databind)
Handles JSON serialization and deserialization.
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonExample {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
User user = new User("Alice", 30);
String json = mapper.writeValueAsString(user);
System.out.println(json); // {"name":"Alice","age":30}
String jsonInput = "{\"name\":\"Bob\",\"age\":28}";
User parsedUser = mapper.readValue(jsonInput, User.class);
System.out.println(parsedUser.getName()); // Bob
// 忽略空字段输出
user.setName(null);
System.out.println(mapper.writeValueAsString(user)); // {"age":30}
}
static class User {
private String name;
private int age;
public User(String name, int age) { this.name = name; this.age = age; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}
}Fastjson (fastjson)
Alibaba’s high‑performance JSON library (note security considerations).
import com.alibaba.fastjson.JSON;
public class FastJsonExample {
public static void main(String[] args) {
User user = new User("Charlie", 22);
String json = JSON.toJSONString(user);
System.out.println(json); // {"age":22,"name":"Charlie"}
String input = "{\"name\":\"David\",\"age\":29}";
User parsed = JSON.parseObject(input, User.class);
System.out.println(parsed.getName()); // David
// 转 Map
String mapJson = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
Map<String, String> map = JSON.parseObject(mapJson, Map.class);
System.out.println(map.get("key1")); // value1
}
static class User {
private String name;
private int age;
public User(String name, int age) { this.name = name; this.age = age; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}
}Conclusion
By judiciously using these utilities you can greatly improve development efficiency and code quality in Spring Boot projects. Prefer Spring’s built‑in utilities or well‑maintained third‑party libraries such as Hutool and Guava, and avoid reinventing the wheel.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
