Spring Data MongoDB身份验证错误

时间:2015-11-05 12:57:37

标签: java spring mongodb spring-mvc spring-data-mongodb

我无法使用spring-data-mongodb插入文档对象。我在spring-mvc项目中配置了MongoDB,如下所示:

__del__

我还添加了存储库和文档。在我的一个控制器中,我插入一个这样的虚拟文档:

@Configuration
@EnableMongoRepositories(basePackages = { "com.example.store.repository" })
public class MongoConfiguration extends AbstractMongoConfiguration {

    @Bean
    public Mongo mongo() throws UnknownHostException {
        ServerAddress serverAddress = new ServerAddress("localhost", 27017);
        MongoCredential credential = MongoCredential.createMongoCRCredential("username", "store", "password".toCharArray());
        MongoClientOptions options = MongoClientOptions.builder().connectionsPerHost(4).socketKeepAlive(true).build();
        Mongo mongo = new MongoClient(serverAddress, Arrays.asList(credential), options);
        return mongo;
    }

    @Bean(name = "MongoTemplate")
    public MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(mongo(), "store");
    }

    @Override
    protected String getDatabaseName() {
        return "store";
    }

} 

当我输入与此方法相对应的网址时,需要几秒钟时间并发出此错误:

@RequestMapping(value="/add", method=RequestMethod.GET)
public String addProduct() {
    Product product = new Product();
    product.setName("New Product");
    product.setDescription("Product Description");
    product.setUnitPrice(19.99);

    productRepository.insert(product);

    return "redirect:/";
}

我无法透露问题。我上面配置了一个用户,我可以在mongo shell中作为该用户进行写入和读取查询。然而,它通过春天失败了。为什么呢?

1 个答案:

答案 0 :(得分:1)

你可以试试这个代码作为MongoConfiguration它可以帮助你,让我知道它是否已经解决了你的问题

@Configuration
@EnableMongoRepositories(basePackages = { "com.example.store.repository" })
public class MongoConfiguration extends AbstractMongoConfiguration {

  @Bean
  public Mongo mongo() throws UnknownHostException {
    return mongoClient();
  }

  @Bean
  public MongoDbFactory mongoDbFactory() {
    return new SimpleMongoDbFactory(mongoClient(), getDatabaseName());
  }

  @Bean
  public MongoTemplate mongoTemplate() {
    return new MongoTemplate(mongoDbFactory(), null);
  }

  @Override
  protected String getDatabaseName() {
    return "store";
  }

  @Bean
  public MongoClient mongoClient() {    
    List<MongoCredential> credentialsList = new ArrayList<MongoCredential>();
    credentialsList.add(MongoCredential.createCredential("username", getDatabaseName(), "password".toCharArray());
    ServerAddress primary = new ServerAddress("localhost", 27017);
    MongoClientOptions mongoClientOptions = MongoClientOptions.builder().connectionsPerHost(4).socketKeepAlive(true).build();
    return new MongoClient(Arrays.aslist(primary), credentialsList, mongoClientOptions); 
  }

}