Master Spring’s Essential Utility Classes: From Resources to AOP
This article provides a comprehensive guide to Spring 5.3.30 utility classes, covering resource handling, object and array utilities, number conversion, stream operations, system property resolution, collection helpers, AOP proxy tools, BeanFactory shortcuts, annotation processing, bean manipulation, validation, XML/HTML parsing, web utilities, and URI handling, all illustrated with clear code examples.
1. Resource Utility Class
The ResourceUtils class offers methods to resolve resource locations to files in the file system.
Read a file from the classpath
<code>File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "logback.xml");</code>Read a file from the file system
<code>file = ResourceUtils.getFile(ResourceUtils.FILE_URL_PREFIX + "D:\\pom.xml");</code>Supported prefixes
<code>public static final String CLASSPATH_URL_PREFIX = "classpath:";
public static final String FILE_URL_PREFIX = "file:";
public static final String JAR_URL_PREFIX = "jar:";
public static final String WAR_URL_PREFIX = "war:";</code>2. Object Utility Class
Convert an object to an array
<code>Object obj = new int[] {1, 2, 3, 4};
Object[] arr = ObjectUtils.toObjectArray(obj);</code>Add a new element to an array
<code>Integer[] obj = new Integer[] {1, 2, 3, 4};
Integer[] ret = ObjectUtils.addObjectToArray(obj, 5);</code>Check if an element exists
<code>Integer[] obj = new Integer[] {1, 2, 3, 4};
boolean exists = ObjectUtils.containsElement(ret, 5);</code>3. Array Conversion
The NumberUtils class provides convenient methods for number conversion and parsing.
Convert to a target type
<code>Number n = 10D;
NumberUtils.convertNumberToTargetClass(n, Double.class);</code>Parse a number
<code>Long ret = NumberUtils.parseNumber("10", Long.class);
System.out.println(ret);</code>4. Stream Operations
Copy a file stream into memory
<code>FileInputStream fis = new FileInputStream(new File("d:\\1.txt"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// File content is now in baos
StreamUtils.copy(fis, baos);</code>Read text content into memory
<code>StreamUtils.copy("abcdef", Charset.forName("UTF-8"), baos);</code>Convert a file stream directly to a String
<code>FileInputStream fis = new FileInputStream(new File("d:\\1.txt"));
String content = StreamUtils.copyToString(fis, Charset.forName("UTF-8"));</code>5. System Property Parsing
Resolve system property placeholders
<code>String home = SystemPropertyUtils.resolvePlaceholders("${java.home}");
System.out.println(home);</code>6. Collection Utility Class
(Illustrated with an image in the original article.)
7. AOP Proxy Utilities
Check if an object is a proxy
<code>static class UserService {}
public static void main(String[] args) {
ProxyFactory factory = new ProxyFactory();
factory.addAdvice(new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
return invocation.proceed();
}
});
factory.setTarget(new UserService());
Object proxy = factory.getProxy();
System.out.println(AopUtils.isAopProxy(proxy));
}</code>Determine if a pointcut can apply to a target class
<code>@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
static @interface Pack {}
static class UserService {
@Pack
public void save() {}
}
// Custom pointcut
Pointcut pc = new Pointcut() {
@Override
public MethodMatcher getMethodMatcher() {
return new AnnotationMethodMatcher(Pack.class);
}
@Override
public ClassFilter getClassFilter() {
return ClassFilter.TRUE;
}
};
boolean ret = AopUtils.canApply(pc, UserService.class);
System.out.println(ret);
</code>Obtain the original target of a proxy
<code>Object proxy = factory.getProxy();
AopProxyUtils.getSingletonTarget(proxy);
</code>8. BeanFactory Utility
Provides convenient methods for operating on a BeanFactory , especially on ListableBeanFactory .
<code>AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.pack");
BeanFactoryUtils.beanOfTypeIncludingAncestors(context, UserDAO.class);
</code>9. Annotation Utility
The AnnotatedElementUtils class offers rich methods to find annotations, meta‑annotations, and repeatable annotations on elements such as methods, fields, or classes.
<code>AnnotatedElementUtils.hasAnnotation(UserService.class, Pack.class);
</code>10. Bean Utility
The BeanUtils class supports bean instantiation, property type checking, property copying, and method discovery.
<code>// Instantiate an object
Person person = BeanUtils.instantiateClass(Person.class);
Person target = new Person();
// Copy properties
BeanUtils.copyProperties(person, target);
// Find a method
Method m = BeanUtils.findMethod(Person.class, "getName");
// Get property descriptor from method
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(Person.class.getDeclaredMethod("getName"));
System.out.println(pd.getName());
</code>11. Data Validation
Spring MVC validation can be performed via annotations or programmatically using ValidationUtils with custom validators.
<code>static class Person {
private Integer age;
private String name;
}
static class PersonValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) { return Person.class.isAssignableFrom(clazz); }
@Override
public void validate(Object target, Errors errors) {
Person p = (Person) target;
if (p.age == null) {
errors.reject("age.empty", "Age cannot be null");
}
}
}
public static void main(String[] args) {
Validator validator = new PersonValidator();
Person target = new Person();
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(target, "person");
ValidationUtils.invokeValidator(validator, target, errors);
System.out.println(errors);
}
</code>12. XML Parsing
The DomUtils class simplifies DOM manipulation.
<code>DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new ClassPathResource("com/pack/main/utils/person.xml").getInputStream());
Element element = document.getDocumentElement();
List<Element> elements = DomUtils.getChildElements(element);
elements.forEach(elt -> System.out.println(elt.getTagName() + "=" + elt.getFirstChild().getNodeValue()));
</code>13. HTML Conversion
The HtmlUtils class provides HTML escaping based on the W3C HTML 4.01 recommendation.
<code>String ret = HtmlUtils.htmlEscape("<script>alert('script')</script>");
System.out.println(ret); // <script>alert('script')</script>
</code>14. Web Utilities
The WebUtils class offers a collection of helpful web‑related methods.
15. URI Handling
Utility methods for working with URIs are provided (illustrated with an image in the original article).
All the above content constitutes the complete article and is intended to help developers work more efficiently with Spring’s utility classes.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
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.