Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register a CustomConverter in a MongoTemplate with Spring Boot

How can I register a custom converter in my MongoTemplate with Spring Boot? I would like to do this only using annotations if possible.

like image 245
Fabio Ebner Avatar asked Oct 05 '16 20:10

Fabio Ebner


People also ask

What is the difference between MongoOperations and MongoTemplate?

MongoTemplate provides a simple way for you to save, update, and delete your domain objects and map those objects to documents stored in MongoDB. You can save, update and delete the object as shown below. MongoOperations is the interface that MongoTemplate implements.

How do you use MongoTemplate aggregation?

To perform and aggregation, first, create aggregation pipelines using the static builder methods on Aggregation class, then create an instance of Aggregation using the newAggregation() method on the Aggregation class and finally run the aggregation using MongoTemplate: MatchOperation matchStage = Aggregation.

What is MongoTemplate spring boot?

The MongoTemplate class is the primary implementation of mongo-operations interface which specifies the basic set of MongoDB operations. We can also use MongoRepository interface to perform MongoDB operations. The implementation class of MongoRepository uses MongoTemplate bean at run time.


3 Answers

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

like image 192
Eugene Avatar answered Oct 04 '22 06:10

Eugene


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
like image 44
Felby Avatar answered Oct 03 '22 06:10

Felby


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);
    }
}
like image 27
Zubair Nabi Avatar answered Oct 04 '22 06:10

Zubair Nabi