NullPointerException when trying to define a custom PropertyMap

后端 未结 3 791
灰色年华
灰色年华 2020-12-21 02:01

I\'m using ModelMapper the following way :

I have a few converter classes that are Spring components and they register custom ModelMapper mappings

@C         


        
相关标签:
3条回答
  • 2020-12-21 02:43

    Autowire using constructor like

    public FooConverter(ModelMapper modelMapper){
       this.modelMapper = modelMapper;
    }
    

    also make sure your ModelMapper bean has been defined in your spring config class like below:

    @Bean
    public ModelMapper modelMapper() {
        return new ModelMapper();
    }
    
    0 讨论(0)
  • 2020-12-21 02:51

    For anyone coming across with the same issue: My problem was that I used PropertyMap with anonymous implementation like the documentation suggested within a spring configuration. This messed up within the ExplicitMappingBuilder. What I have now is the following:

    @Configuration
    public class ApplicationConfig {
    
        @Bean
        public ModelMapper modelMapper() {
            ModelMapper modelMapper = new ModelMapper();
            modelMapper.addMappings(new UserPropertyMap());
            return modelMapper;
        }
    }
    

    My UserPropertyMap looks like this:

    public class UserPropertyMap extends PropertyMap<UserRepresentation, UserDTO> {
        @Override
        protected void configure() {
            map().setUserName(source.getUsername());
        }
    }
    

    This worked like a charm in Spring Boot 2.

    0 讨论(0)
  • 2020-12-21 02:52

    I think this is ultimately due to the fact that ModelMapper can not instantiate TimeZone objects (nor LocalDateTime etc.) at the time of configuring the mapper.

    Actually you don't have to configure anything.

    ModelMapper mapper = new ModelMapper();
    
    Foo foo = new Foo();
    foo.setTimeZone(TimeZone.getDefault());
    
    FooModel model = mapper.map(foo, FooModel.class);
    System.out.println(model.getTimeZoneId()); // "Europe/Berlin" here
    

    This works for me. ModelMapper found out that you want to map the TimeZone's property ID to FooModel's property timeZoneId.

    Nevertheless, just in case you want to do that manually: Following the docs quickly, I found the concept of converters. Using a Converter which converts TimeZone to String you can do this:

    ModelMapper mapper = new ModelMapper();
    TypeMap<Foo, FooModel> typeMap = mapper.createTypeMap(Foo.class, FooModel.class);
    Converter<TimeZone, String> tzConverter = ctx -> ctx.getSource().getID() + "!!!";
    typeMap.addMappings(map -> {
        map.using(tzConverter).map(Foo::getTimeZone, FooModel::setTimeZoneId);
    });
    
    Foo foo = new Foo();
    foo.setTimeZone(TimeZone.getDefault());
    
    FooModel model = mapper.map(foo, FooModel.class);
    System.out.println(model.getTimeZoneId()); // "Europe/Berlin!!!" here
    
    0 讨论(0)
提交回复
热议问题