无法在spring中配置正确的mongo db名称

时间:2016-08-03 13:09:44

标签: java spring mongodb spring-boot

我目前正在使用MongoDB和Spring。 虽然配置了另一个db,但它仍然尝试从错误的db创建/读取。

这是我的代码:

foreach ( [
              [
                  'itemable_id' => 1,
                  'label' => 'Home',
                  'left' => 1,
                  'right' => 2
              ],
              [
                  'itemable_id' => 2,
                  'label' => 'About Us',
                  'left' => 3,
                  'right' => 4
              ]
          ] as $arr )
{
    /* @var $page Page */
    $page = Page::findOrFail($arr['itemable_id']);

处理程序:

@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");
  }
}

log.info()的输出:

@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");
  }
}

正如你所看到的,mongo对象指的是test.user,但为什么呢? 是否需要更多配置? db测试也是由spring创建的。

1 个答案:

答案 0 :(得分:1)

由于您使用的是春季启动,因此您只需使用其auto-configuration capabilities - 将以下行添加到spring.data.mongodb.uri=mongodb://localhost/gabble 文件中:

MongoConfig

并完全删除var request = require('request'); exports.index = function (req, res) { res.render('home', { title: 'home' }); }; 课程。