I do not want to utilize the Spring DATA MongoDB support. I want to leverage the ORM for MongoDB called Morphia.
https://github.com/mongodb/morphia
I want to configure the Morphia with Spring Boot. I want to externalize the configuration of Morphia in a way that it follows the Spring Boot philosophy.
I want to leverage the environment variables for the configuration of Morphia properties.
What would be the Spring Boot approach to achieve this ?
In a simple main program on would do following to get the Morhpia ORM working.
private Morphia morphia;
private MongoClient mongoClient;
morphia = new Morphia();
// Person is an entity object with Morphia annotations
morphia.map(Person.class);
// THESE properties MUST be read from environment variables in Spring BOOT.
final String host = "localhost";
final int port = 27017;
mongoClient = new MongoClient(host, port);
//Set database
// this instance would be autowired all data access classes
Datastore ds = morphia.createDatastore(mongoClient, "dataStoreInstanceId");
// this is how instance would be used in those data accesses classes
Person p = ds.find(Person.class, "username", "john").get();
The Spring Boot like approach would be to create a AutoConfiguration with the needed properties which creates an instance of Datastore
as bean.
In the Reference Guide you will find how to set properties and connect to a MongoDB.
An AutoConfiguration for Morphia could look like this:
@Configuration
public class MorphiaAutoConfiguration {
@Autowired
private MongoClient mongoClient; // created from MongoAutoConfiguration
@Bean
public Datastore datastore() {
Morphia morphia = new Morphia();
// map entities, there is maybe a better way to find and map all entities
ClassPathScanningCandidateComponentProvider entityScanner = new ClassPathScanningCandidateComponentProvider(true);
entityScanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class));
for (BeanDefinition candidate : scanner.findCandidateComponents("your.basepackage")) { // from properties?
morphia.map(Class.forName(candidate.getBeanClassName()));
}
return morphia.createDatastore(mongoClient, "dataStoreInstanceId"); // "dataStoreInstanceId" may come from properties?
}
}
You could then autowire your Datastore in other Spring beans the usual way:
@Autowired
private Datastore datastore;
If some points are not correct or unclear just take a look at the existing *AutoConfiguration
classes in Spring Boot.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With