Spring provides a number of small helper (“utility”) classes (e.g. StringUtils, ClassUtils, CollectionUtils, Assert
, etc.) in org.springframework.util
. Some of these are purely internal helpers for the framework itself; others are exposed to developers as convenient tools to reduce boilerplate. As the Spring team notes:
“Spring offers several utility classes in the frameworks themselves, potentially sparing you a dependency.”
That said, the Javadocs often mention “mainly for internal use within the framework” (for example, in CollectionUtils
) — meaning one should use them judiciously, understanding their contract and stability.
Also, in some cases, external libraries (Apache Commons, Guava, etc.) may offer richer or more robust versions, so it’s good to compare.
Below is a survey of the most commonly used Spring util
classes, along with tutorials / examples.
1. StringUtils
Probably the most often-used utility in org.springframework.util
. It offers null-safe string operations beyond what String
itself provides.
Key methods & behavior
Method | Purpose / Description |
---|---|
hasLength(String) / hasLength(CharSequence)
|
Check that the input is not null and length > 0 |
hasText(String) / hasText(CharSequence)
|
Check that input has non-whitespace characters (i.e. not null, not blank) |
containsWhitespace(...) |
Whether the input contains any whitespace character |
trimAllWhitespace(...) |
Remove all whitespace (leading, trailing, in-between) |
delete(String inString, String pattern) |
Remove all occurrences of a substring |
deleteAny(String inString, String charsToDelete) |
Remove any of the given characters |
replace(...) |
Classic substring replacement |
tokenizeToStringArray(...) |
Split a String by delimiters, with options to trim tokens / ignore empties |
delimitedListToStringArray(...) |
Split by a fixed delimiter (e.g. CSV) |
commaDelimitedListToStringArray(...) / commaDelimitedListToSet(...)
|
CSV parsing into array or set (removes duplicates) |
arrayToDelimitedString(...) / arrayToCommaDelimitedString(...)
|
Reverse: join an array or collection into a delimited string |
capitalize(...) / uncapitalize(...) / uncapitalizeAsProperty(...)
|
Change first character case appropriately |
cleanPath(...) |
Normalize a path, e.g. handling “../” segments |
applyRelativePath(...) |
Apply a relative path (e.g. when combining resource paths) |
getFilename(...) , getFilenameExtension(...) , stripFilenameExtension(...)
|
Extract or strip file name parts |
parseLocale(String) , parseLocaleString(...) , parseTimeZoneString(...)
|
Parsing Locale or TimeZone from string representations |
quote(...) / quoteIfString(...)
|
Wrap with single quotes (if string) |
substringMatch(...) , startsWithIgnoreCase(...) , endsWithIgnoreCase(...) etc. |
Additional matching utilities |
truncate(CharSequence, int) |
Truncate a long string with “(truncated)…” suffix |
Example usage:
String s = " Hello, Spring ";
if ( !StringUtils.hasText(s) ) {
// s is either null, empty, or only whitespace
}
String trimmed = StringUtils.trimAllWhitespace(s); // "Hello,Spring"
String[] parts = StringUtils.tokenizeToStringArray("a, b, , c", ",", true, true);
// parts = ["a", "b", "c"]
String path = StringUtils.cleanPath("/foo/../bar/./spam");
// path = "/bar/spam"
String filename = StringUtils.getFilename("/foo/bar/test.txt"); // "test.txt"
String ext = StringUtils.getFilenameExtension("test.txt"); // "txt"
String joined = StringUtils.arrayToDelimitedString(new String[]{"a","b","c"}, ";");
// joined = "a;b;c"
Caveats & notes:
In Spring 5 onward, some older methods (like
isEmpty(Object)
inStringUtils
) are deprecated in favor ofhasLength
/hasText
etc.It is not a full-featured string toolkit; if you need advanced string manipulations (e.g. Levenshtein distance, more powerful splitting, substring diff, etc.), libraries like Apache Commons Lang’s
StringUtils
may be more appropriate.The Javadoc for some Spring utility classes explicitly warns “Mainly for internal use … consider Jakarta’s Commons Lang for a more comprehensive suite”
2. Assert
A simple, lightweight assertion / validation helper (not to be confused with Java’s assert
keyword). It’s often used to defend method arguments, enforce invariants, and fail fast with clear messages.
Key methods & behavior
Some common methods:
-
Assert.notNull(Object obj, String message)
— throwIllegalArgumentException
ifobj
is null -
Assert.isTrue(boolean expression, String message)
— throw if expression is false -
Assert.hasLength(String text, String message)
— throw iftext
is null or empty -
Assert.hasText(String text, String message)
— throw if it has no non-whitespace text -
Assert.isInstanceOf(Class<?> type, Object obj, String message)
— ensure object is instance of given class -
Assert.isAssignable(Class<?> superType, Class<?> subType, String message)
— check class assignability -
Assert.noNullElements(Object[] array, String message)
— check no nulls in an array -
Assert.notEmpty(Collection<?> collection, String message)
— check the collection is not null and non-empty -
Assert.notEmpty(Map<?,?> map, String message)
— similar for maps -
Assert.state(boolean expression, String message)
— same asisTrue
, but used for internal state conditions
Example usage:
public void processOrder(Order order) {
Assert.notNull(order, "Order must not be null");
Assert.hasText(order.getId(), "Order ID must not be empty");
Assert.isTrue(order.getAmount() > 0, "Amount must be positive");
…
}
If one of the assertions fails, an IllegalArgumentException
is thrown, with your message.
Use cases:
- Validating public method parameters
- Internal invariants (preconditions / postconditions)
- Guard checks before performing logic
Caveats:
- This is a “fail fast” mechanism; it’s not a substitute for full validation logic (e.g. user input validation).
- Because Spring removed or deprecated some older
Assert
methods over versions, migrating between versions sometimes requires adapting code.
3. CollectionUtils
Utilities around Collection
, Map
, Iterator
, Enumeration
. Useful for null-safe operations or combining collections.
Key methods & behavior
Method | Description |
---|---|
isEmpty(Collection<?> c) / isEmpty(Map<?,?> m)
|
Null-safe “is empty or null” check (i.e. returns true if null or empty) |
firstElement(List<T>) / lastElement(List<T>) / firstElement(Set<T>) / lastElement(Set<T>)
|
Convenient retrieval of first/last (or null if none) |
contains(Iterator<?> it, Object element) / contains(Enumeration<?> en, Object element)
|
Check if the iterator / enumeration has the element |
containsAny(Collection<?> source, Collection<?> candidates) |
True if any element in candidates is in source
|
containsInstance(Collection<?> coll, Object instance) |
Checks by identity (==), not equals |
findFirstMatch(Collection<?> source, Collection<E> candidates) |
Return first element in candidates that is in source
|
findValueOfType(...) , findValueOfType(Collection, Class<T>)
|
Search by type, return single matching value if clear, else null |
hasUniqueObject(Collection<?>) |
True if only a single instance is present (or multiple references to same instance) |
mergeArrayIntoCollection(Object array, Collection<E> coll) |
Add all elements of the array to the collection |
mergePropertiesIntoMap(Properties props, Map<K,V> map) |
Copy key/value pairs from Properties into a map |
newHashMap(int expectedSize) / newLinkedHashMap(int expectedSize)
|
Create maps sized appropriately avoiding immediate rehash |
toIterator(Enumeration<E>) / toArray(Enumeration<?>, A[] arr)
|
Convert Enumeration to iterator / array |
Many others like compositeMap(...) , etc. |
Example usage:
List<String> list = null;
if (!CollectionUtils.isEmpty(list)) {
// safe: won't NPE
}
List<String> a = List.of("a", "b");
List<String> b = List.of("x", "b", "y");
String match = CollectionUtils.findFirstMatch(b, a);
// match = "b"
Set<Integer> s = Set.of(1,2,3);
Integer first = CollectionUtils.firstElement(s);
String[] arr = new String[] {"x","y"};
CollectionUtils.mergeArrayIntoCollection(arr, someList);
Caveats & notes:
- Because
isEmpty
is null-safe, using it reduces the boilerplateif (c != null && !c.isEmpty())
pattern. - The Javadoc warns that many methods in
CollectionUtils
are “mainly for internal use within the framework.” ([Home][9]) - In some large or functional-style codebases, more advanced collection handling (Streams, Guava’s
Multiset
/ImmutableListSet
, etc.) may overshadow the need for many of these utilities. - Overuse can lead to hiding nulls / masking potential bugs; only use where clarity and safety benefit.
4. ClassUtils
Utilities dealing with Java Class
/ reflection / naming / resource paths.
Key methods & behavior
Method | Description |
---|---|
forName(String className, ClassLoader cl) |
Load a class by name, with fallback class loader logic |
getMethod(Class<?> clazz, String methodName, Class<?>... paramTypes) |
Similar to Class.getMethod , but wraps NoSuchMethodException into unchecked IllegalStateException
|
classNamesToString(Class<?>... classes) / classNamesToString(Collection<Class<?>> classes)
|
Build comma-separated names |
classPackageAsResourcePath(Class<?> clazz) |
Convert a class’s package to resource path (e.g. com.foo.Bar → com/foo ) |
addResourcePathToPackagePath(Class<?> clazz, String resourceName) |
Combine package path and resource name properly |
getShortName(Class<?>) / getShortNameAsProperty(...)
|
Short class name (without package) or property-format version (first letter lower case) |
isPresent(String className, ClassLoader classLoader) |
Check if a class name is present on classpath |
isAssignable(...) |
Check type assignment compatibility (with primitive / wrapper handling) |
isPrimitiveOrWrapper(Class<?>) |
Whether a class is primitive or its wrapper (e.g. int , Integer ) |
getPackageName(Class<?>) / getUserClass(Class<?>) etc. |
Example usage:
if (ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", null)) {
// Jackson is on the classpath
}
Method m = ClassUtils.getMethod(MyBean.class, "setName", String.class);
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Class<?> cls = ClassUtils.forName("com.example.Foo", cl);
String pkgPath = ClassUtils.classPackageAsResourcePath(MyBean.class);
// e.g. "com/example"
String propName = ClassUtils.getShortNameAsProperty(MyBean.class);
// e.g. "myBean"
Caveats & notes:
- Be mindful of class loader issues (especially in container / application servers) when using
forName
orisPresent
. - As always, exceptions thrown by reflection should be caught or wrapped properly if exposing to layers above.
- Overuse of reflection / dynamic class loading can erode compile-time safety; use these utilities when necessary.
5. Other noteworthy Spring util / core-utility classes
While the ones above are among the most commonly used, here are a few additional helpful utilities in Spring or its companion modules:
-
BeanUtils
(inorg.springframework.beans
) — copying properties between beans, instantiating beans, etc. -
ReflectionUtils
(inorg.springframework.util
/org.springframework.core
) — scanning and invoking fields, methods reflectively -
ClassPathResource
,FileSystemResource
,Resource
abstraction (inorg.springframework.core.io
) — uniform resource access -
AopUtils
(inorg.springframework.aop.support
) — for AOP-related introspection (like “is proxy” / “get ultimate target class”) -
ResolvableType
(inorg.springframework.core
) — for working with generics / parameterized types at runtime -
StopWatch
(inorg.springframework.util
) — a simple performance-measuring utility (start/stop timer) -
PropertyPlaceholderHelper / PropertyPlaceholderHelper
— for parsing placeholders in strings (e.g.${…}
)
These typically live outside org.springframework.util
but are part of Spring’s “helper toolset.”
Putting it all into a learning path / tutorial plan
If you want a self-paced learning / tutorial to really internalize these utility classes, here is a suggested roadmap:
-
Set up a small Spring project (Spring Boot or plain Spring) and include a module named, say,
spring-utils-demo
. -
Exercise
StringUtils
:
- Write unit tests for various corner cases (null, empty, whitespace-only, CSV strings, path normalization)
-
Try to replicate parts of its behavior manually to see the boilerplate it avoids
-
Use
Assert
in your code:
-
Use
In service / utility methods, add precondition checks using
Assert
-
See how errors are thrown and how stack traces look
-
Play with
CollectionUtils
:
-
Play with
Test null-safety, merging arrays, first/last element retrieval
-
Write a small method that finds a matching element from one list in another
-
Use
ClassUtils
/ reflection utilities:
-
Use
Dynamically load a class by name and invoke a method
-
Get the “short name as property” of classes
- Compare with alternatives:
-
For similar tasks, try Apache Commons (e.g.
org.apache.commons.lang3.StringUtils
,CollectionUtils
, etc.) and see strengths/weaknesses- Read the source:
-
Because these utility classes are relatively small, browse their source code in your IDE to understand corner-case handling
- Be version-aware:
Some utility methods get deprecated / removed or relocated over Spring versions; test your code across versions if you plan upgrades.
Top comments (0)