【问题标题】:Static use of Dozer MapperDozer Mapper 的静态使用
【发布时间】:2013-03-15 10:34:20
【问题描述】:

只是想知道这样的静态推土机映射器是否会导致并发错误:

public static Mapper mapper = new DozerBeanMapper();
public static MyDTO toDTO(MyEntity e) {
    MyDTO dto = mapper.map(e, MyDTO.class);
    return dto;
}

或者我应该总是使用这个代码:

public static MyDTO toDTO(MyEntity e) {
    Mapper mapper = new DozerBeanMapper();
    MyDTO dto = mapper.map(e, MyDTO.class);
    return dto;
}

该方法用于JBoss Server 的@Stateless session bean,可以并发访问。事实是我真的不知道 Dozer 是否使用库中的静态变量或实例变量来决定我是否可以/应该使用静态 Mapper 或在每次调用时创建一个新实例。

【问题讨论】:

    标签: jboss mapping dozer stateless-session-bean


    【解决方案1】:

    Dozer 实例可以是静态的。如果您为每个请求创建新实例,性能会更差,因为每次都会初始化大量缓存。由于自定义转换器中的错误或内部推土机问题,可能会遇到并发错误。

    【讨论】:

    • 我目前不使用自定义转换器。因此,我应该是安全的。我将为静态实例更改代码。
    【解决方案2】:

    documentation 开始,DozerMapper 实例应该构建为单例。 DozerBeanMapper 是线程安全的,因此您可以不顾风险地使用多个线程。

    确保您也可以使用DozerBeanMapperSingletonWrapper.getInstance(); 这将为您处理单例部分。

    我认为将映射器用作公共静态字段并不是一个好主意。

    您也可以使用Selma 来处理您的映射。这是一个基于 Annotation 处理器的新库,可在编译时生成映射代码。有了它,您的代码将如下所示:

    // Configure the mapping
    @Mapper
    public interface DtoMapper {
    
        MyDTO toDTO(MyEntity e);
    }
    
    // Retrieve the mapper 
    public static DtoMapper mapper = Selma.getMapper(DtoMapper.class);
    
    // and some where in the code use
    mapper.toDto(entity);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      • 1970-01-01
      相关资源
      最近更新 更多