问题
How can I register a custom converter in my MongoTemplate with Spring Boot? I would like to do this only using annotations if possible.
回答1:
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);
}
}
回答2:
I just register the bean:
@Bean
public MongoCustomConversions mongoCustomConversions() {
List list = new ArrayList<>();
list.add(myNewConverter());
return new MongoCustomConversions(list);
}
Here is a place in source code where I find it
回答3:
If you only want to override the custom converters portion of the Spring Boot configuration, you only need to create a configuration class that provides a @Bean for the custom converters. This is handy if you don't want to override all of the other Mongo settings (URI, database name, host, port, etc.) that Spring Boot has wired in for you from your application.properties file.
@Configuration
public class MongoConfig
{
@Bean
public CustomConversions customConversions()
{
List<Converter<?, ?>> converterList = new ArrayList<Converter<?, ?>>();
converterList.add(new MyCustomWriterConverter());
return new CustomConversions(converterList);
}
}
This will also only work if you've enabled AutoConfiguration and excluded the DataSourceAutoConfig:
@SpringBootApplication(scanBasePackages = {"com.mypackage"})
@EnableMongoRepositories(basePackages = {"com.mypackage.repository"})
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
public class MyApplication
{
public static void main(String[] args)
{
SpringApplication.run(MyApplication.class, args);
}
}
In this case, I'm setting a URI in the application.properties file and using Spring data repositories:
#mongodb settings
spring.data.mongodb.uri=mongodb://localhost:27017/mydatabase
spring.data.mongodb.repositories.enabled=true
来源:https://stackoverflow.com/questions/39883134/register-a-customconverter-in-a-mongotemplate-with-spring-boot