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
File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "logback.xml");Read a file from the file system
file = ResourceUtils.getFile(ResourceUtils.FILE_URL_PREFIX + "D:\\pom.xml");Supported prefixes
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:";2. Object Utility Class
Convert an object to an array
Object obj = new int[] {1, 2, 3, 4};
Object[] arr = ObjectUtils.toObjectArray(obj);Add a new element to an array
Integer[] obj = new Integer[] {1, 2, 3, 4};
Integer[] ret = ObjectUtils.addObjectToArray(obj, 5);Check if an element exists
Integer[] obj = new Integer[] {1, 2, 3, 4};
boolean exists = ObjectUtils.containsElement(ret, 5);3. Array Conversion
The NumberUtils class provides convenient methods for number conversion and parsing.
Convert to a target type
Number n = 10D;
NumberUtils.convertNumberToTargetClass(n, Double.class);Parse a number
Long ret = NumberUtils.parseNumber("10", Long.class);
System.out.println(ret);4. Stream Operations
Copy a file stream into memory
FileInputStream fis = new FileInputStream(new File("d:\\1.txt"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// File content is now in baos
StreamUtils.copy(fis, baos);Read text content into memory
StreamUtils.copy("abcdef", Charset.forName("UTF-8"), baos);Convert a file stream directly to a String
FileInputStream fis = new FileInputStream(new File("d:\\1.txt"));
String content = StreamUtils.copyToString(fis, Charset.forName("UTF-8"));5. System Property Parsing
Resolve system property placeholders
String home = SystemPropertyUtils.resolvePlaceholders("${java.home}");
System.out.println(home);6. Collection Utility Class
(Illustrated with an image in the original article.)
7. AOP Proxy Utilities
Check if an object is a proxy
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));
}Determine if a pointcut can apply to a target class
@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);Obtain the original target of a proxy
Object proxy = factory.getProxy();
AopProxyUtils.getSingletonTarget(proxy);8. BeanFactory Utility
Provides convenient methods for operating on a BeanFactory, especially on ListableBeanFactory.
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.pack");
BeanFactoryUtils.beanOfTypeIncludingAncestors(context, UserDAO.class);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.
AnnotatedElementUtils.hasAnnotation(UserService.class, Pack.class);10. Bean Utility
The BeanUtils class supports bean instantiation, property type checking, property copying, and method discovery.
// 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());11. Data Validation
Spring MVC validation can be performed via annotations or programmatically using ValidationUtils with custom validators.
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);
}12. XML Parsing
The DomUtils class simplifies DOM manipulation.
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()));13. HTML Conversion
The HtmlUtils class provides HTML escaping based on the W3C HTML 4.01 recommendation.
String ret = HtmlUtils.htmlEscape("<script>alert('script')</script>");
System.out.println(ret); // <script>alert('script')</script>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.
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.
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.
