java – How to connect Spring MVC to a remote MongoDB, to use the MongoOperations interface?
java – How to connect Spring MVC to a remote MongoDB, to use the MongoOperations interface?
If you want you can use a java class to configure mongoDB rather than an XML file.
The code below uses spring-boot and spring-data-mongo in order to access a remote MongoDB > 3.X instance.
@Configuration
@EnableMongoRepositories()
public class MongoConfig extends AbstractMongoConfiguration {
@Value(${spring.data.mongodb.port})
private Integer port;
@Value(${spring.data.mongodb.host})
private String ip;
@Value(${spring.data.mongodb.database})
private String database;
@Value(${spring.data.mongodb.username})
private String username;
@Value(${spring.data.mongodb.password})
private String password;
@Value(${spring.data.mongodb.authenticationDatabase})
private String authDb;
@Override
protected String getDatabaseName() {
return database;
}
@Bean(name = mongoClient)
public MongoClient mongo() throws UnknownHostException {
String connection = String.format(mongodb://%s:%s@%s/%s, username, password, ip, authDb);
return new MongoClient(new MongoClientURI(connection));
}
}
Then inside your view or service you can simply inject the bean mongoClient
I will assume that you are using MongoDB 3.x. The connection options for Mongo in Spring are
<mongo:mongo-client id=mongoClient host=${mongo.host} port=${mongo.port} credentials=user:password@database>
<mongo:client-options ... />
</mongo:mongo-client>
<mongo:db-factory dbname=database mongo-ref=mongoClient/>
More here: Spring Data MongoDB – Reference Documentation
The section related to authentication is: 17.1.3. Authentication
In your particular case (using options from your example) it should be the following
<mongo:mongo-client id=mongoClient host=10.11.12.13 port=27017 credentials=root:123456@admin>
<mongo:db-factory dbname=MockDB mongo-ref=mongoClient/>
P.S. It is generally recommended to use <mongo:mongo-client>
instead <mongo:mongo>
for 3.x version.
java – How to connect Spring MVC to a remote MongoDB, to use the MongoOperations interface?
lets Try this may be it will resolve your problem
<mongo:mongo host=${mongoDBHost} port=${mongoDBPort} id=mongo />
<bean id=mongoCredientials class=org.springframework.data.authentication.UserCredentials>
<constructor-arg name=username value=${mongoDBUserName}/>
<constructor-arg name=password value=${mongoDBPassword}/>
</bean>
<bean id=mongoDbFactory class=org.springframework.data.mongodb.core.SimpleMongoDbFactory>
<constructor-arg name=mongo ref=mongo/>
<constructor-arg name=databaseName value=${mongoDBName}/>
<constructor-arg name=credentials ref=mongoCredientials/>
</bean>
<mongo:mapping-converter id=mappingConverter db-factory-ref=mongoDbFactory />
<bean id=mongoTemplate class=org.springframework.data.mongodb.core.MongoTemplate>
<constructor-arg name=mongoDbFactory ref=mongoDbFactory/>
<constructor-arg name=mongoConverter ref=mappingConverter/>
</bean>