How can I register a custom converter in my MongoTemplate with Spring Boot? I would like to do this only using annotations if possible.
You need to create a configuration class for converter config.
@Configuration
@EnableAutoConfiguration(exclude = { EmbeddedMongoAutoConfiguration.class })
@Profile("!testing")
public class MongoConfig extends AbstractMongoConfiguration {
@Value("${spring.data.mongodb.host}") //if it is stored in application.yml, else hard code it here
private String host;
@Value("${spring.data.mongodb.port}")
private Integer port;
@Override
protected String getDatabaseName() {
return "test";
}
@Bean
public Mongo mongo() throws Exception {
return new MongoClient(host, port);
}
@Override
public String getMappingBasePackage() {
return "com.base.package";
}
@Override
public CustomConversions customConversions() {
List<Converter<?, ?>> converters = new ArrayList<>();
converters.add(new LongToDateTimeConverter());
return new CustomConversions(converters);
}
}
@ReadingConverter
static class LongToDateTimeConverter implements Converter<Long, Date> {
@Override
public Date convert(Long source) {
if (source == null) {
return null;
}
return new Date(source);
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments