简体   繁体   中英

cant config correct mongo db name in spring

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM