Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autowiring into JPA converters

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?

like image 714
falcon Avatar asked Apr 26 '16 05:04

falcon


People also ask

What is JPA attribute converter?

If you don't need to provide a custom JDBC binding and fetching logic, then the JPA AttributeConverter is a viable solution to define the mapping between a given Java Object type and a database column type.

Does spring convert all values to target data types?

Spring provides out-of-the-box various converters for built-in types; this means converting to/from basic types like String, Integer, Boolean and a number of other types. Apart from this, Spring also provides a solid type conversion SPI for developing our custom converters.

What is converter in spring boot?

A converter converts a source object of type S to a target of type T . Implementations of this interface are thread-safe and can be shared.

Which of the following annotations support the automatic conversion of exceptions from one type to another?

The @Repository annotation can have a special role when it comes to converting database exceptions to Spring-based unchecked exceptions.


1 Answers

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;
    }
    .....
    .....
}
like image 50
xierui Avatar answered Nov 02 '22 04:11

xierui