Boost Your Java Backend: Essential Spring Utility Classes Explained
This article introduces the most useful Spring framework utility classes—including Assert, StringUtils, CollectionUtils, ObjectUtils, ClassUtils, BeanUtils, ReflectionUtils, Base64Utils, SerializationUtils, HttpStatus, and HtmlUtils—providing clear explanations, code examples, and practical tips to improve development efficiency and code quality.
Assert
Spring provides the Assert class for making assertions that throw exceptions when conditions are not met.
1.1 Assert null or not null
String str = null;
Assert.isNull(str, "str must be null");
Assert.notNull(str, "str must not be null");Violations raise IllegalArgumentException.
1.2 Assert collection emptiness
List<String> list = null;
Map<String, String> map = null;
Assert.notEmpty(list, "list cannot be empty");
Assert.notEmpty(map, "map cannot be empty");Violations raise IllegalArgumentException.
1.3 Assert boolean condition
List<String> list = null;
Assert.isTrue(CollectionUtils.isNotEmpty(list), "list cannot be empty");StringUtils
Spring’s StringUtils extends JDK string handling.
2.1 Check length
if (!StringUtils.hasLength("")) {
System.out.println("String is empty");
}2.2 Remove all whitespace
@Test
public void testEmpty() {
System.out.println("1" + StringUtils.trimAllWhitespace(" 苏三说技术 测试 ") + "1");
}Result:
1苏三说技术测试12.3 Starts/ends with ignore case
@Test
public void testEmpty() {
System.out.println(StringUtils.startsWithIgnoreCase("苏三说技术", "苏三"));
System.out.println(StringUtils.endsWithIgnoreCase("苏三说技术", "技术"));
}Both statements print true.
2.4 Collection to comma‑delimited string
@Test
public void testEmpty() {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
System.out.println(StringUtils.collectionToCommaDelimitedString(list));
}Output:
a,b,cCollectionUtils
Utility methods for collection handling.
3.1 Check if collection is empty
List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);
if (CollectionUtils.isEmpty(list)) {
System.out.println("Collection is empty");
}3.2 Check element existence
List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);
if (CollectionUtils.contains(list.iterator(), 3)) {
System.out.println("Element exists");
}Note: iterator() is required.
ObjectUtils
Provides powerful null‑safe operations.
4.1 Null‑safe emptiness check
@Test
public void testEmpty() {
String a = "123";
Integer b = new Integer(1);
List<String> c = new ArrayList<>();
c.add(a);
Map<String, String> e = new HashMap<>();
e.put(a, a);
Optional<String> f = Optional.of(a);
if (!ObjectUtils.isEmpty(a)) System.out.println("a is not empty");
if (!ObjectUtils.isEmpty(b)) System.out.println("b is not empty");
if (!ObjectUtils.isEmpty(c)) System.out.println("c is not empty");
if (!ObjectUtils.isEmpty(e)) System.out.println("e is not empty");
if (!ObjectUtils.isEmpty(f)) System.out.println("f is not empty");
}4.2 Null‑safe equality
@Test
public void testEquals() {
String a = "123";
String b = null;
System.out.println(ObjectUtils.nullSafeEquals(a, b));
}Prints false without NPE.
4.3 Identity hash code
@Test
public void testIdentityHex() {
String a = "123";
System.out.println(ObjectUtils.getIdentityHexString(a));
}Example output:
2925bf5bClassUtils
Utility methods for class metadata.
5.1 Get all interfaces of an object
Class<?>[] allInterfaces = ClassUtils.getAllInterfaces(new User());5.2 Get package name
String packageName = ClassUtils.getPackageName(User.class);
System.out.println(packageName);5.3 Check if class is inner
System.out.println(ClassUtils.isInnerClass(User.class));5.4 Check if object is a CGLIB proxy
System.out.println(ClassUtils.isCglibProxy(new User()));BeanUtils
JavaBean manipulation utilities.
6.1 Copy properties
User user1 = new User();
user1.setId(1L);
user1.setName("苏三说技术");
user1.setAddress("成都");
User user2 = new User();
BeanUtils.copyProperties(user1, user2);
System.out.println(user2);6.2 Instantiate class via reflection
User user = BeanUtils.instantiateClass(User.class);
System.out.println(user);6.3 Find declared method
Method declaredMethod = BeanUtils.findDeclaredMethod(User.class, "getId");
System.out.println(declaredMethod.getName());6.4 Find method’s property descriptor
Method declaredMethod = BeanUtils.findDeclaredMethod(User.class, "getId");
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(declaredMethod);
System.out.println(pd.getName());ReflectionUtils
Reflection helper methods.
7.1 Find method
Method method = ReflectionUtils.findMethod(User.class, "getId");7.2 Find field
Field field = ReflectionUtils.findField(User.class, "id");7.3 Invoke method
ReflectionUtils.invokeMethod(method, springContextsUtil.getBean(beanName), param);7.4 Check if field is public static final
Field field = ReflectionUtils.findField(User.class, "id");
System.out.println(ReflectionUtils.isPublicStaticFinal(field));7.5 Check if method is equals
Method method = ReflectionUtils.findMethod(User.class, "getId");
System.out.println(ReflectionUtils.isEqualsMethod(method));Base64Utils
Encode and decode data using Base64.
String str = "abc";
String encode = new String(Base64Utils.encode(str.getBytes()));
System.out.println("Encoded: " + encode);
try {
String decode = new String(Base64Utils.decode(encode.getBytes()), "utf8");
System.out.println("Decoded: " + decode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}Output: Encoded: YWJj and
Decoded: abcSerializationUtils
Simplify object serialization.
Map<String, String> map = Maps.newHashMap();
map.put("a", "1");
map.put("b", "2");
map.put("c", "3");
byte[] serialize = SerializationUtils.serialize(map);
Object deserialize = SerializationUtils.deserialize(serialize);
System.out.println(deserialize);HttpStatus
Standard HTTP status codes are available via org.springframework.http.HttpStatus or org.apache.http.HttpStatus, eliminating the need to define custom constants.
HtmlUtils
Escape HTML special characters to prevent XSS and injection attacks.
@Test
public void testHtml() {
String specialStr = "<div id=\"testDiv\">test1;test2</div>";
String escaped = HtmlUtils.htmlEscape(specialStr);
System.out.println(escaped);
}Result:
<div id="testDiv">test1;test2</div>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.
Su San Talks Tech
Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.
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.
