跳转到主内容
websoft网络软件专家 - 深耕网络技术,打造实用软件!

Java BeanUtils 类作用、语法与示例详解

目录

一、BeanUtils 的核心作用

二、Apache Commons BeanUtils

核心方法

三、Spring BeanUtils

核心方法(更简洁高效)

四、最佳实践与注意事项

1. 选择指南

2. 性能对比

3. 常见问题解决

五、实际应用场景

场景1:DTO/VO 转换场景2:表单对象绑定场景3:动态配置注入场景4:对象合并总结:BeanUtils 作用

一、BeanUtils 的核心作用

BeanUtils是 Apache Commons 和 Spring Framework 提供的工具类,主要用于简化 JavaBean 的操作

。核心功能包括:

属性拷贝:对象间同名属性自动复制动态访问:通过字符串名称操作属性类型转换:自动处理不同类型间的转换嵌套访问:支持address.city格式的链式访问📌JavaBean 定义:符合规范的 POJO 类有无参构造函数属性私有化提供 getter/setter 方法

二、Apache Commons BeanUtils

核心方法方法作用示例copyProperties(dest, orig)复制同名属性BeanUtils.copyProperties(userDTO, user);getProperty(bean, name)获取属性值String name = BeanUtils.getProperty(user, "name");setProperty(bean, name, value)设置属性值BeanUtils.setProperty(user, "age", "30");describe(bean)对象转 MapMap map = BeanUtils.describe(user);populate(bean, properties)Map 转对象BeanUtils.populate(user, map);使用示例// 添加依赖// // commons-beanutils// commons-beanutils// 1.9.4// import org.apache.commons.beanutils.BeanUtils;public class CommonsExample {public static void main(String[] args) throws Exception {// 1. 创建源对象User source = new User("Alice", 25, new Address("New York"));// 2. 创建目标对象UserDTO target = new UserDTO();// 3. 属性拷贝(同名属性自动复制)

BeanUtils.copyProperties(target, source);System.out.println(target);// 输出: UserDTO{name='Alice', age=25, city='New York'}// 4. 动态获取属性String city = BeanUtils.getProperty(source, "address.city");System.out.println(city); // 输出: New York// 5. 动态设置属性BeanUtils.setProperty(target, "age", "30"); // 字符串自动转int// 6. 对象转Map Map map = BeanUtils.describe(source);System.out.println(map);// {name=Alice, age=25, address=Address[city=New York]}// 7. Map转对象Map data = new HashMap<>();data.put("name", "Bob");data.put("age", "35"); // 字符串自动转换data.put("address.city", "London"); // 嵌套属性User newUser = new User();BeanUtils.populate(newUser, data);System.out.println(newUser.getAddress().getCity()); // 输出: London}}// JavaBean 类class User {private String name;private int age;private Address address;// 无参构造器、getter/setter 省略}class UserDTO {private String name;private int age;private String city; // 对应 address.city// 无参构造器、getter/setter 省略}class Address {private String city;// 构造器、getter/setter 省略}

三、Spring BeanUtils

核心方法(更简洁高效)

方法作用特点copyProperties(source, target)属性复制无类型转换,性能更好copyProperties(source, target, ignoreProperties)带忽略属性的复制跳过指定属性使用示例// 添加依赖// // org.springframework// spring-beans// 5.3.20// import org.springframework.beans.BeanUtils;public class SpringExample {public static void main(String[] args) {User source = new User("Alice", 25, new Address("New York"));UserDTO target = new UserDTO();// 1. 基础属性复制BeanUtils.copyProperties(source, target);System.out.println(target.getCity()); // 输出: null (不自动处理嵌套)// 2. 带忽略属性的复制BeanUtils.copyProperties(source, target, "age"); // 忽略age属性System.out.println(target.getAge()); // 输出: 0 (默认值)// 3. 自定义属性处理器class CustomConverter implements Converter {public Object convert(Class type, Object value) {if(value instanceof User) {return ((User) value).getAddress().getCity();}return null;}}// 4. 处理嵌套属性(需自定义)

String city = (String) new CustomConverter().convert(String.class, source);target.setCity(city);System.out.println(target.getCity()); // 输出: New York}}

四、最佳实践与注意事项

1. 选择指南

场景推荐工具需要类型转换Apache BeanUtils高性能场景Spring BeanUtils嵌套属性访问Apache BeanUtils简单属性复制Spring BeanUtils

2. 性能对比

3. 常见问题解决

问题1:嵌套属性复制失败// Apache 解决方案BeanUtils.setProperty(target, "address.city", "Paris");// Spring 解决方案(需自定义)

class AddressMapper {public static void map(User source, UserDTO target) {target.setCity(source.getAddress().getCity());}}问题2:类型转换错误// 注册自定义转换器ConvertUtils.register(new Converter() {public Object convert(Class type, Object value) {return LocalDate.parse(value.toString());}}, LocalDate.class);// 现在可以处理字符串转LocalDate BeanUtils.setProperty(target, "birthDate", "2023-01-01");问题3:忽略特定属性// Spring 方式BeanUtils.copyProperties(source, target, "password", "sensitiveData");// Apache 方式(需额外处理)

Map map = BeanUtils.describe(source);map.remove("password");BeanUtils.populate(target, map);

五、实际应用场景

场景1:DTO/VO 转换// Controller层public UserDTO getUser(Long id) {User user = userService.findById(id);UserDTO dto = new UserDTO();BeanUtils.copyProperties(user, dto);return dto;}场景2:表单对象绑定// 接收表单提交public String createUser(@ModelAttribute UserForm form) {User user = new User();BeanUtils.copyProperties(form, user);userService.save(user);return "redirect:/users";}场景3:动态配置注入// 从配置文件中读取设置@Value("${app.settings}") private Map settings;public void applySettings() {AppConfig config = new AppConfig();BeanUtils.populate(config, settings);}场景4:对象合并public User mergeUserChanges(User original, User changes) {User merged = new User();BeanUtils.copyProperties(original, merged); // 复制原始数据BeanUtils.copyProperties(changes, merged); // 覆盖变更数据return merged;}总结:BeanUtils 作用消除样板代码:减少 getter/setter 调用提升开发效率:简化对象操作增强灵活性:支持动态属性访问降低耦合度:解耦对象操作逻辑您可能感兴趣的文章:java反射机制及beanUtils的实现原理分析Java中BeanUtils.copyProperties()详解及应用场景java使用BeanUtils.copyProperties方法对象复制同名字段类型不同赋值为空问题解决方案java中BeanUtils.copyProperties的用法(超详细) Java中BeanUtils.copyProperties的11个坑总结Java BeanUtils工具类常用方法讲解java Beanutils.copyProperties( )用法详解Java类库BeanUtils组件使用方法及实例详解Java工具类BeanUtils库介绍及实例详解

相关文章