Unlock 24 Powerful Spring Boot Utilities with Real‑World Code Samples
This article introduces 24 essential Spring Boot utility classes—covering bean handling, AOP support, core framework helpers, and common I/O and conversion tools—providing concise explanations and runnable code snippets that demonstrate how each utility simplifies everyday backend development.
Introduction
In daily development, utility classes act like a Swiss‑army‑knife, encapsulating high‑frequency functions such as string handling, date calculations, and collection operations so developers can avoid repetitive code. Spring Framework ships with a rich set of built‑in utilities that replace dozens of lines of custom logic with a single call.
Practical Cases
2.1 Bean‑related Utilities (spring‑beans)
The spring-beans package provides four useful classes.
BeanUtils
Static methods for bean instantiation, property copying, type checking, etc.
/**1. Object property copy */
User source = new User(1L, "PackXg");
User target = new User();
BeanUtils.copyProperties(source, target);
/**2. Instantiate bean */
User instance = BeanUtils.instantiateClass(User.class);
/**3. Check simple value type */
Class<?> type = User.class.getDeclaredField("name").getType();
bool isSimple = BeanUtils.isSimpleValueType(type);Additional methods are available for advanced bean manipulation.
BeanFactoryUtils
Convenient operations on ListableBeanFactory, such as retrieving bean counts, names, or instances, and handling nested factory hierarchies.
ListableBeanFactory beanFactory = ...;
CommonDAO dao = BeanFactoryUtils.beanOfType(beanFactory, CommonDAO.class);
String[] beanNames = BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors(beanFactory, Pack.class);
Map<String, CommonDAO> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(beanFactory, CommonDAO.class);BeanFactoryAnnotationUtils
Utility for locating beans annotated with specific qualifiers.
// Define beans
@Component
@Qualifier("product")
public class ProductDAO implements CommonDAO {}
@Component
@Qualifier("user")
public class UserDAO implements CommonDAO {}
ConfigurableListableBeanFactory beanFactory = ...;
CommonDAO userDAO = BeanFactoryAnnotationUtils.qualifiedBeanOfType(beanFactory, CommonDAO.class, "user");
CommonDAO productDAO = BeanFactoryAnnotationUtils.qualifiedBeanOfType(beanFactory, CommonDAO.class, "product");BeanDefinitionReaderUtils
Support for programmatic bean definition registration.
BeanDefinitionRegistry registry = ...;
AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(UserDAO.class).getBeanDefinition();
String beanName = BeanDefinitionReaderUtils.generateBeanName(beanDefinition, registry);
BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, beanName);
BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);2.2 AOP‑related Utilities (spring‑aop)
AopConfigUtils
Registers automatic proxy creators for AOP infrastructure.
BeanDefinitionRegistry registry = ...;
AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);AopProxyUtils
Helper methods to obtain the original target object behind a proxy and to list user‑defined interfaces.
UserDAO proxy = ...;
Object target = AopProxyUtils.getSingletonTarget(proxy);
Class<?>[] interfaces = AopProxyUtils.proxiedUserInterfaces(proxy);AutoProxyUtils
Determines the target class for a bean and whether class‑based proxying is required.
ConfigurableListableBeanFactory beanFactory = ...;
Class<?> targetClass = AutoProxyUtils.determineTargetClass(beanFactory, "userDAO");
boolean shouldProxy = AutoProxyUtils.shouldProxyTargetClass(beanFactory, "userDAO");ScopedProxyUtils
Creates scoped proxies used by @Scope annotations.
try (GenericApplicationContext context = new GenericApplicationContext()) {
BeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(UserDAO.class).getBeanDefinition();
BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, "userDAO");
BeanDefinitionHolder scopedProxy = ScopedProxyUtils.createScopedProxy(holder, context, true);
context.registerBeanDefinition("userDAO", scopedProxy.getBeanDefinition());
context.refresh();
UserDAO dao = context.getBean(UserDAO.class);
System.err.println(dao.getClass());
}ClassFilters
Combines multiple ClassFilter instances for flexible matching.
ClassFilter f1 = clazz -> clazz.getPackageName().startsWith("com.pack.aop");
ClassFilter f2 = clazz -> clazz.isAssignableFrom(CommonDAO.class);
ClassFilter union = ClassFilters.union(new ClassFilter[]{f1, f2});
ClassFilter negated = ClassFilters.negate(f1);
ClassFilter intersect = ClassFilters.intersection(new ClassFilter[]{f1, f2});AopUtils
Utility methods for AOP proxy inspection.
UserDAO userDAO = ...;
Class<?> targetClass = AopUtils.getTargetClass(userDAO);
boolean isProxy = AopUtils.isAopProxy(userDAO);
Advisor advisor = ...;
boolean applicable = AopUtils.canApply(advisor, UserDAO.class);ClassUtils
Miscellaneous helpers for java.lang.Class operations.
Class<?> clazz = ClassUtils.forName("com.pack.utils.zdomain.User", ClassUtilsTest.class.getClassLoader());
Method method = ClassUtils.getMethod(clazz, "getId");
Class<?>[] interfaces = ClassUtils.getAllInterfaces(new UserDAO());2.3 Core Spring Utilities (spring‑core)
ReflectUtils
Reflection‑based helpers for instance creation, method lookup, and property descriptor retrieval.
UserDAO instance = ReflectUtils.newInstance(UserDAO.class);
Method m = ReflectUtils.findDeclaredMethod(UserDAO.class, "create", new Class[]{String.class});
PropertyDescriptor[] getters = ReflectUtils.getPropertyDescriptors(UserDAO.class);ResourcePatternUtils
Determines whether a location string can be resolved by a ResourcePatternResolver.
String loc = "classpath:com/pack.properties";
boolean isUrl = ResourcePatternUtils.isUrl(loc);DigestUtils
Computes hash digests such as MD5.
String hex = DigestUtils.md5DigestAsHex("Spring Boot3实战案例200讲".getBytes());
System.err.println(hex);LogFormatUtils
Formats objects for logging, optionally truncating output.
String out = LogFormatUtils.formatValue(new User(1L, "PackXg"), false);
String truncated = LogFormatUtils.formatValue(new User(1L, "PackXg"), 10, true);
Log logger = LogFactory.getLog(User.class);
LogFormatUtils.traceDebug(logger, () -> "Spring Boot3实战案例200讲");PropertiesLoaderUtils
Convenient loading of java.util.Properties resources.
Properties props = PropertiesLoaderUtils.loadAllProperties("pack.properties");
Resource res = new ClassPathResource("pack.properties");
PropertiesLoaderUtils.fillProperties(new Properties(), res);AnnotatedElementUtils
Finds annotations, meta‑annotations, and repeatable annotations on classes, methods, fields, etc.
Set<Component> comps = AnnotatedElementUtils.findAllMergedAnnotations(UserDAO.class, Component.class);
MultiValueMap<String, Object> attrs = AnnotatedElementUtils.getAllAnnotationAttributes(UserDAO.class, Qualifier.class.getName());OrderUtils
Determines order values from @Order or @Priority annotations.
Integer order = OrderUtils.getOrder(UserDAO.class);
order = OrderUtils.getOrder(AppConfig.class.getMethod("userDAO"));FileCopyUtils
Simple file and stream copy utilities.
byte[] data = "Spring Boot3实战案例200讲".getBytes(StandardCharsets.UTF_8);
FileCopyUtils.copy(data, new File("f:/1.txt"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileCopyUtils.copy(data, baos);
byte[] read = FileCopyUtils.copyToByteArray(new File("f:/1.txt"));
System.err.println(new String(read, StandardCharsets.UTF_8));FileSystemUtils
Recursive copy and delete operations on the file system.
FileSystemUtils.copyRecursively(src, dest);
FileSystemUtils.deleteRecursively(src);MimeTypeUtils
Parsing and constants for MIME types.
MimeType mt = MimeTypeUtils.parseMimeType("application/json");
System.err.println(mt);NumberUtils
Number parsing and conversion helpers.
Double d = NumberUtils.parseNumber("20", Double.class);
Integer i = NumberUtils.convertNumberToTargetClass(20, Integer.class);StreamUtils
Stream copying utilities that leave streams open.
StreamUtils.copy(in, out);
byte[] bytes = StreamUtils.copyToByteArray(in);StringUtils
String‑handling utilities such as length checks and whitespace detection.
boolean hasLen = StringUtils.hasLength(s);
boolean hasWs = StringUtils.containsWhitespace(s);
String[] arr = StringUtils.toStringArray(List.of("a", "b", "c"));Images Illustrating Core Concepts
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.
