dozer 学习 日志

第一种:xml 配置

  注入一个工具类 dozerBeanMapper到spring上下文环境中 并指定映射文件的位置

 1 @Configuration
 2 public class DozerBeanMapperConfiguer {
 3 
 4     @Bean(name = "org.dozer.Mapper")
 5     public DozerBeanMapper dozer() {
 6         //这里是配置文件的路径
 7         List<String> mappingFiles = Arrays.asList("dozer/dozer-mapping.xml");
 8         DozerBeanMapper dozerBean = new DozerBeanMapper();
 9         dozerBean.setMappingFiles(mappingFiles);
10         return dozerBean;
11     }
12 }

  在resourc 包下创建 dozer/dozer-mapping.xml 文件 

<?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns="http://dozer.sourceforge.net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://dozer.sourceforge.net
          http://dozer.sourceforge.net/schema/beanmapping.xsd">
    <mapping>
        <class-a>top.nosoul.generator.User</class-a>
        <class-b>top.nosoul.model.UserVo</class-b>
        <field>
            <a>username</a>
            <b>dozerName</b>
        </field>
    </mapping>

</mappings>

  xml配置的方法 支持字符串和日期的映射 date-format:指定日期格式

<field>
  <a date-format="MM/dd/yyyy HH:mm:ss:SS">dateString</a>
  <b>dateObject</b>
</field>

  使用:

      在serverImpl类中注入并且在方法中调用

 1 @Resource DozerBeanMapper dozerBeanMapper; 

 

 1 User user = dozerBeanMapper.map(userVo,User.class); 

 

第二种:注入一个工具类 dozerBeanMapper到spring上下文环境中 并指定映射文件的位置

1 @Configuration
2 public class DozerBeanMapperConfiguer {
3 
4     @Bean
5     public DozerBeanMapper mapper() {
6         DozerBeanMapper dozerBean = new DozerBeanMapper();
7         return dozerBean;
8     }
9 }

  在souceBean中用注解的方式映射

1     @Mapping("dozerUid")
2     private Integer uid;

 

  在serverImap类中注入并且在方法中调用         注意xml配置是DozerBeanMapper        注解是mapper

1     @Autowired
2     Mapper dozerBeanMapper;

 

 list映射可以配置dozer工具 

 1 public class DozerUtils
 2 {  
 3 
 4 
 5 private static DozerBeanMapper dozer = new DozerBeanMapper();  
 6 
 7   public static <T> List<T> mapList(Collection sourceList, Class<T> destinationClass)  
 8   {  
 9     List destinationList = Lists.newArrayList();  
10     for (Iterator i$ = sourceList.iterator(); i$.hasNext(); ) { Object sourceObject = i$.next();  
11       Object destinationObject = dozer.map(sourceObject, destinationClass);  
12       destinationList.add(destinationObject);  
13     }  
14     return destinationList;  
15   }  
16   
17 }

使用方法:直接调用

1 List<UserVo> userVos = DozerUtils.mapList(users, UserVo.class);

 

  

posted @ 2020-03-26 21:05  无魂儿  阅读(310)  评论(0)    收藏  举报