12

I am using a customized ObjectMapper in my spring boot app. I also use the JPA converters for several fields which are stored as JSON strings in the DB. I am not sure how to autowire my custom object mapper into my converter.

@Convert(converter=AddressConverter.class)
private Address address;

And my AddressConverter is

class AddressConverter implements AttributeConverter<Address, String> {

        @Autowire
        ObjectMapper objectMapper; //How to do this?
        .....
        .....
   }

How to autowire ObjectMapper into AddressConverter? Is there a way to do this with Spring AOP?

falcon
  • 1,332
  • 20
  • 39
  • This is a duplicate of https://stackoverflow.com/questions/47219421/accessing-spring-beans-inside-attributeconverter-class which has more details. – Matthew Wise Sep 10 '20 at 16:35

1 Answers1

23

Maybe you can do it by changing it to a static property, like this:

@Component
class AddressConverter implements AttributeConverter<Address, String> {

    private static ObjectMapper objectMapper; 

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper){
        AddressConverter.objectMapper = objectMapper;
    }
    .....
    .....
}
acdcjunior
  • 132,397
  • 37
  • 331
  • 304
xierui
  • 1,047
  • 1
  • 9
  • 22
  • 1
    This did work for me. Although I also had to add the annotation `@Converter` and make sure the Converter is autowired somewhere else so that spring actually initialized it. – n0daft Aug 24 '16 at 15:29
  • I tried this and it doesn't work. Tried n0daft's suggestions as well, but the field is always null. – Mat DeLong Oct 05 '17 at 14:21
  • I am also having troubles with Spring Data JPA project, I found there should be some kind of override converters.add method, but still in issue state... :-( – kensai Oct 16 '17 at 23:40
  • 1
    It worked for me too, but I'm not able to understand how, can you please explain. – thekosmix May 10 '18 at 12:07
  • Why does field needs to be static? Please explain – chill appreciator Oct 04 '19 at 22:53
  • I believe this is related to how Hibernate handles AttributeConverters' lifecycle. Having a static attribute for the mapper makes all instances of AddressConverter -in this example- share the same autowired mapper. – tete Feb 10 '20 at 13:25
  • really good way – Amna Irshad Sipra Oct 15 '21 at 19:41