Reputation: 736
Im currently diving in MongoDB and Spring. Although another db is configured, it still tries to create/read from the wrong db.
Here's my code:
@Configuration
@EnableMongoRepositories
public class MongoConfig {
@Bean
public MongoClientFactoryBean mongo() {
MongoClientFactoryBean mongo = new MongoClientFactoryBean();
mongo.setHost("localhost");
return mongo;
}
@Bean
public MongoOperations mongoTemplate(Mongo mongo) {
return new MongoTemplate(mongo, "gabble");
}
}
Handler:
@Component
public class SomeHandler {
private static final Logger log = Logger.getLogger(SomeHandler.class);
private MongoOperations mongo;
@Autowired
public SomeHandler(MongoOperations mongo) {
this.mongo = mongo;
}
public void registerNewUser(User user, Credential credential) {
log.info(mongo.getCollectionNames());
mongo.save(user,"user");
mongo.save(credential,"credential");
log.info("count: "+mongo.getCollection("user").count());
log.info("content: "+mongo.getCollection("user").find());
log.info("stored new user in database");
}
}
the output of log.info():
2016-08-03 14:46:13 INFO SomeHandler:29 - count: 1
2016-08-03 14:46:13 INFO SomeHandler:30 - content: Cursor id=0, ns=test.user, query={ }, numIterated=0, readPreference=primary
As you can see, mongo object refers to test.user, but why ? Is there more configuration needed ? The db test gets also created by spring.
Upvotes: 1
Views: 646
Reputation: 6646
Since you are using spring boot, you can just use its auto-configuration capabilities - add the following line to the application.properties
file:
spring.data.mongodb.uri=mongodb://localhost/gabble
and remove the MongoConfig
class entirely.
Upvotes: 2