dozer介绍
dozer用于对象之间属性的复制,避免复杂的get/set方法
如何使用
添加依赖
1 2 3 4 5
| <dependency> <groupId>com.github.dozermapper</groupId> <artifactId>dozer-spring-boot-starter</artifactId> <version>6.5.0</version> </dependency>
|
配置
dozer默认存在隐性映射,相同属性名将自动进行映射,如果属性名不相同需要通过注解/xml进行自定义配置.
注解
1 2 3 4
| class Demo{ @Mapping("address") private String addr; }
|
如果项目中对象映射很复杂,或者存在一对多映射关系,此方式不适用,因此不建议.
xml
xml路径和文件名称可自定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <?xml version="1.0" encoding="UTF-8"?> <mappings xmlns="http://dozermapper.github.io/schema/bean-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://dozermapper.github.io/schema/bean-mapping http://dozermapper.github.io/schema/bean-mapping.xsd">
<configuration> <date-format>yyyy-MM-dd HH:mm:ss</date-format> </configuration> <mapping wildcard="true"> <class-a>com.huang.dozer.bean.User</class-a> <class-b>com.huang.dozer.bean.UserXmlDestinationObject</class-b> <field> <a>name</a> <b>username</b> </field> <field> <a>birthday</a> <b>dateOfBirth</b> </field> </mapping> </mappings>
|
初始化
1 2 3 4 5 6 7 8 9
| @Configuration public class DozerConfig { @Bean public DozerBeanMapperFactoryBean dozerMapper(@Value("classpath:dozer/*.xml") Resource[] resources) throws IOException { DozerBeanMapperFactoryBean dozerBeanMapperFactoryBean = new DozerBeanMapperFactoryBean(); dozerBeanMapperFactoryBean.setMappingFiles(resources); return dozerBeanMapperFactoryBean; } }
|
将dozer mapper加入到spring容器管理
使用
1 2 3 4 5 6 7 8 9 10
| public class Demo{ @Autowired private Mapper mapper;
public void test{ SysUser sysUser = new SysUser(); sysUser.setUsername("demo"); SysUserInfoDto sysUserInfoDto = mapper.map(sysUser, SysUserInfoDto.class); } }
|