SoFunction
Updated on 2025-04-27

Use of 49 commonly used tool classes built in SpringBoot

SpringBoot has become the preferred framework for Java development with its powerful automatic configuration and rich ecosystem.

In addition to core functionality, SpringBoot and its dependencies also contain a large number of practical tool classes that can significantly simplify daily development.

This article will introduce 49 common tool classes and show their basic usage through concise code examples.

String processing tool class

1. StringUtils

import ;

// Check whether the string is emptyboolean isEmpty = (null);  // true
boolean isEmpty2 = ("");  // true

// Check if the string has text contentboolean hasText = ("  ");  // false
boolean hasText2 = ("hello");  // true

// Split stringString[] parts = ("a,b,c", ",");

// Clear the beginning and end blanksString trimmed = ("  hello  ");  // "hello"

2. AntPathMatcher

import ;

AntPathMatcher matcher = new AntPathMatcher();
boolean match1 = ("/users/*", "/users/123");  // true
boolean match2 = ("/users/**", "/users/123/orders");  // true
boolean match3 = ("/user?", "/user1");  // true

// Extract path variablesMap<String, String> vars = (
    "/users/{id}", "/users/42");  // {id=42}

3. PatternMatchUtils

import ;

boolean matches1 = ("user*", "username");  // true
boolean matches2 = ("user?", "user1");  // true
boolean matches3 = (
    new String[]{"user*", "admin*"}, "username");  // true

4. PropertyPlaceholderHelper

import ;

PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper("${", "}");
Properties props = new Properties();
("name", "World");
("greeting", "Hello ${name}!");

String result = ("${greeting}", props::getProperty);
// "Hello World!"

Collection and array tool classes

5. CollectionUtils

import ;

// Check whether the collection is emptyboolean isEmpty = (null);  // true
boolean isEmpty2 = (());  // true

// Collection operationList<String> list1 = ("a", "b", "c");
List<String> list2 = ("b", "c", "d");
Collection<String> intersection = (list1, list2);  // [b, c]

// Merge collectionsList<String> target = new ArrayList<>();
(new String[]{"a", "b"}, target);

6. MultiValueMap

import ;
import ;

MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
("colors", "red");
("colors", "blue");
("sizes", "large");

List<String> colors = ("colors");  // [red, blue]

7. ConcurrentReferenceHashMap

import ;

// Create reference maps in high concurrency scenarios (similar to WeakHashMap but thread-safe)Map&lt;String, Object&gt; cache = new ConcurrentReferenceHashMap&lt;&gt;();
("key1", new LargeObject());

8. SystemPropertyUtils

import ;

// parse strings containing system attributesString javaHome = ("${}");
String pathWithDefault = (
    "${:default}");  // "default"

Reflection and class processing tools

9. ReflectionUtils

import ;

// Get the field of the classField field = (, "name");
(field);
(field, person, "John");

// Call methodMethod method = (, "setAge", );
(method);
(method, person, 30);

// Field callback(, field -&gt; {
    (());
});

10. ClassUtils

import ;

// Get the class nameString shortName = ("");  // "MyClass"

// Check if the class existsboolean exists = ("", null);  // true

// Get all interfacesClass&lt;?&gt;[] interfaces = ();

// Get user-defined class loaderClassLoader classLoader = ();

11. MethodInvoker

import ;

MethodInvoker invoker = new MethodInvoker();
(new MyService());
("calculateTotal");
(new Object[]{100, 0.2});
();
Object result = ();

12. BeanUtils

import ;

// Copy propertiesPerson source = new Person("John", 30);
Person target = new Person();
(source, target);

// Instantiate the classPerson newPerson = ();

// Find methodMethod method = (, "setName", );

I/O and Resource Tools

13. FileCopyUtils

import ;

// Copy the file contentsbyte[] bytes = (new File(""));
(bytes, new File(""));

// Read textString content = (
    new InputStreamReader(new FileInputStream(""), "UTF-8"));

// Stream copy(inputStream, outputStream);

14. ResourceUtils

import ;

// Get the fileFile file = ("classpath:");

// Check if it is a URLboolean isUrl = ("");

// Get URLURL url = ("classpath:");

15. StreamUtils

import ;

// Streaming operationbyte[] data = (inputStream);
String text = (inputStream, StandardCharsets.UTF_8);
(inputStream, outputStream);
("Hello", StandardCharsets.UTF_8, outputStream);

16. FileSystemUtils

import ;

// Delete the directoryboolean deleted = (new File("/tmp/test"));

// Copy the directory(new File("source"), new File("target"));

17. ResourcePatternUtils

import ;
import ;
import ;

// Get matching resourcesResource[] resources = (
    new PathMatchingResourcePatternResolver())
    .getResources("classpath*:META-INF/*.xml");

Web related tool classes

18. WebUtils

import ;
import ;

// Get CookiesCookie cookie = (request, "sessionId");

// Get the request pathString path = (request);

// Get parameters from the requestint pageSize = (request, "pageSize", 10);

19. UriUtils

import ;

// Codec URI componentString encoded = ("path with spaces", "UTF-8");
String decoded = (encoded, "UTF-8");

20. UriComponentsBuilder

import ;

// Build URIURI uri = ("")
    .path("/products")
    .queryParam("category", "books")
    .queryParam("sort", "price")
    .build()
    .toUri();

21. ContentCachingRequestWrapper

import ;
import ;

ContentCachingRequestWrapper wrapper = new ContentCachingRequestWrapper(request);
// After the request is processedbyte[] body = ();

22. HtmlUtils

import ;

// HTML escapeString escaped = ("&lt;script&gt;alert('XSS')&lt;/script&gt;");
// &amp;lt;script&amp;gt;alert('XSS')&amp;lt;/script&amp;gt;

// HTML inversionString unescaped = ("&amp;lt;b&amp;gt;Bold&amp;lt;/b&amp;gt;");
// &lt;b&gt;Bold&lt;/b&gt;

Verification and Assertion Tools

23. Assert

import ;

// Common assertions(object, "Object must not be null");
(name, "Name must not be empty");
(amount &gt; 0, "Amount must be positive");
(items, "Items must not be empty");
(isInitialized, "Service is not initialized");

24. ObjectUtils

import ;

// Object Toolboolean isEmpty = (null);  // true
boolean isEmpty2 = (new String[0]);  // true

String nullSafe = (null);  // "null"
boolean equals = (obj1, obj2);

// default valueString value = (null, "default");

25. NumberUtils

import ;

// Digital conversionInteger parsed = ("42", );
Double converted = (42, );

Date and Time Tools

26. DateTimeUtils

import ;
import ;

// Format dateString formatted = ().format(new Date());

27. StopWatch

import ;

// Timing toolStopWatch watch = new StopWatch("TaskName");
("phase1");
// Execute task 1(100);
();

("phase2");
// Execute task 2(200);
();

// Output report(());
("Total time: " + () + "ms");

Safety-related tools

28. DigestUtils

import ;

// MD5 hashString md5 = DigestUtils.md5DigestAsHex("password".getBytes());

// File MD5String fileMd5;
try (InputStream is = new FileInputStream("")) {
    fileMd5 = DigestUtils.md5DigestAsHex(is);
}

29. Base64Utils

import .Base64Utils;

// Base64 codecbyte[] data = "Hello World".getBytes();
String encoded = (data);
byte[] decoded = (encoded);

30. CryptoUtils

import ;
import ;

// Text encryptionString password = "secret";
String salt = "deadbeef";
TextEncryptor encryptor = (password, salt);
String encrypted = ("Message");
String decrypted = (encrypted);

JSON and data conversion tools

31. JsonUtils

import ;
import ;

// JSON parsingJsonParser parser = ();
Map&lt;String, Object&gt; parsed = ("{"name":"John", "age":30}");
List&lt;Object&gt; parsedList = ("[1, 2, 3]");

32. TypeUtils

import ;

// Type analysisResolvableType type = ();
ResolvableType elementType = (0);

// Generic type processingResolvableType mapType = (
    , , );

33. MappingJackson2HttpMessageConverter

import .MappingJackson2HttpMessageConverter;
import ;

// Custom JSON converterObjectMapper mapper = new ObjectMapper();
// Configure mapperMappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(mapper);

Other practical tools

34. RandomStringUtils

import .;

// Random string generationString random = (10);
String randomLetters = (8);
String randomNumeric = (6);

35. CompletableFutureUtils

import ;
import ;
import ;

// Merge multiple CompletableFuture resultsList&lt;CompletableFuture&lt;String&gt;&gt; futures = /* Multiple asynchronous operations */;
CompletableFuture&lt;List&lt;String&gt;&gt; allResults = (
    (new CompletableFuture[0]))
    .thenApply(v -&gt; ()
        .map(CompletableFuture::join)
        .collect(()));

36. CacheControl

import ;
import ;

// Cache controlCacheControl cacheControl = (1, )
    .noTransform()
    .mustRevalidate();

String headerValue = ();

37. AnnotationUtils

import ;

// Find annotationsComponent annotation = (, );

// Get annotation attributesString value = (annotation, "value").toString();

// Merge annotationsComponent mergedAnnotation = (
    annotation, );

38. DefaultConversionService

import ;

// Type conversionDefaultConversionService conversionService = new DefaultConversionService();
String strValue = "42";
Integer intValue = (strValue, );

39. HeaderUtils

import ;

// HTTP header processingHttpHeaders headers = new HttpHeaders();
("Content-Type", "application/json");
(1024);
("max-age=3600");

40. MediaTypeFactory

import ;
import ;
import ;

// Infer media type based on file nameOptional&lt;MediaType&gt; mediaType = ("");
// application/pdf

41. MimeTypeUtils

import ;

// MIME type constants and parsingboolean isCompatible = MimeTypeUtils.APPLICATION_JSON.isCompatibleWith(
    MimeTypeUtils.APPLICATION_JSON_UTF8);

42. WebClientUtils

import ;
import ;

// Create a WebClientWebClient webClient = ()
    .baseUrl("")
    .defaultHeader("Authorization", "Bearer token")
    .filter((
        clientRequest -&gt; {
            // Request processing            return (clientRequest);
        }))
    .build();

43. PropertySourceUtils

import ;
import ;

// Add attribute sourceStandardEnvironment env = new StandardEnvironment();
Map&lt;String, Object&gt; map = new HashMap&lt;&gt;();
("", "MyApp");
().addFirst(new MapPropertySource("my-properties", map));

44. EventPublishingUtils

import ;

// Publish an eventApplicationEventPublisher publisher = /* Get publisher */;
(new CustomEvent("Something happened"));

45. LocaleContextHolder

import .;
import ;

// Get/set the current localeLocale currentLocale = ();
();

46. AopUtils

import ;

// AOP tool methodboolean isAopProxy = (bean);
boolean isCglibProxy = (bean);
Class&lt;?&gt; targetClass = (bean);

47. ProxyUtils

import ;

// Create a proxyProxyFactory factory = new ProxyFactory(targetObject);
();
(new MyMethodInterceptor());
MyInterface proxy = (MyInterface) ();

48. ClassPathScanningCandidateComponentProvider

import ;

// Scan the classpathClassPathScanningCandidateComponentProvider scanner = 
    new ClassPathScanningCandidateComponentProvider(true);
(new AnnotationTypeFilter());
Set&lt;BeanDefinition&gt; beans = ("");

49. YamlUtils

import ;
import ;

// parse YAML filesYamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
(new ClassPathResource(""));
Properties properties = ();

Summarize

These tool classes cover most common scenarios in Java development, from basic string processing to advanced reflection operations, from file IO to secure encryption, from web development to performance monitoring.

Proficiency in these tools can significantly improve development efficiency, reduce boilerplate code, and help write more robust applications.

In daily development, it is recommended to develop the habit of viewing Spring and SpringBoot documents and explore more useful tool classes.

The above is the detailed content of the 49 commonly used tool classes built in SpringBoot. For more information about SpringBoot’s built-in tool classes, please follow my other related articles!