Skip to content
广告❤️成为赞助商

Converters

Allows customizing the conversion strategy for certain fields of the final JavaBean.

Notes:

  • You can customize the conversion strategy for specific fields of the final JavaBean. For example, some values stored in the database may be special, such as time values. When querying from MongoDB, they might be of type Date, but you may want to receive them as LocalDateTime and apply a custom conversion strategy (the framework already supports this).
  • When using a converter, you need to register the converter class as a Spring Bean and set the generic type to specify the type the converter handles.

ConversionStrategy

  • This interface defines a converter. All converters should implement this interface by implementing the convertValue(Field field, Object obj, Object fieldValue) method.
  • fieldValue: the value of the field
  • fieldType: the type of the field
  • mongoConverter: the converter instance

Example

First, implement the ConversionStrategy interface, set the generic type to the target class, and register it as a Spring Bean (in this example, we use @Component). Avoid using proxy classes for the converter implementation.
java
// Register as Spring Bean
@Component
public class LocalDateTimeConversionStrategy implements ConversionStrategy<LocalDateTime> {}
Next, implement the convertValue method from the ConversionStrategy interface to define your conversion logic:
java
// Register as Spring Bean
@Component
public class LocalDateTimeConversionStrategy implements ConversionStrategy<LocalDateTime> {
    @Override
    public LocalDateTime convertValue(Object fieldValue, Class<?> fieldType, MongoConverter mongoConverter) throws IllegalAccessException {
        return fieldValue.getClass().equals(Long.class) ?
                InstantUtil.convertTimestampToLocalDateTime((Long) fieldValue) :
                InstantUtil.convertTimestampToLocalDateTime8(((Date) fieldValue).toInstant());
    }
}