Spring整合MongoTemplate

xml形式的整合



    
    
    
    
    
    
    
         
    
    
    
    
    
       
    

由于公司用的是dubbo容器,所以需要使用代码的方式实现(类似于springboot)

String host ="your host";
        Integer port = "your port";
        String username = "username";
        String defaultDataBaseName = "default database name";
        String password = "password";

        //address
        ServerAddress address = new ServerAddress(host, port);

        //client
        MongoCredential mongoCredential = MongoCredential.createCredential(username, defaultDataBaseName, password.toCharArray());
        LinkedList mongoCredentials = Lists.newLinkedList();
        mongoCredentials.add(mongoCredential);
        MongoClient client = new MongoClient(address, mongoCredentials);
        client.setWriteConcern(WriteConcern.SAFE);

        //factory
        SimpleMongoDbFactory factory = new SimpleMongoDbFactory(client, defaultDataBaseName);

        //template
        MongoTemplate template = new MongoTemplate(factory);

        mongoTemplate = template;

以上代码只要在容器加载的时候,执行一遍, 就可以实现了.

你可能感兴趣的:(Spring整合MongoTemplate)