I have the following working configurations in my Spring application:
<mongo:mongo id="myRs" replica-set="myhost:27017">
<mongo:options max-wait-time="1500"
connect-timeout="30000" />
</mongo:mongo>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<property name="writeResultChecking" value="EXCEPTION"/>
<property name="writeConcern" value="FSYNC_SAFE"/>
<constructor-arg ref="myRs"/>
<constructor-arg name="databaseName" value="mydb"/>
</bean>
Now all I want to do is to set up username/password for accessing the mongo database without changing my code (i.e. only by updating the Spring app context xml file). Is that possible? If so, how?
Thanks.
You can pass username password like this to MongoTemplate. Using PropertyPlaceholderConfigurer you can even read the username and password from a property file.
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<property name="writeResultChecking" value="EXCEPTION"/>
<property name="writeConcern" value="FSYNC_SAFE"/>
<constructor-arg ref="myRs"/>
<constructor-arg name="databaseName" value="mydb"/>
<constructor-arg name="userCredentials" ref="userCredentials"/>
</bean>
<bean id="userCredentials" class="org.springframework.data.authentication.UserCredentials">
<constructor-arg name="username" value="username" />
<constructor-arg name="password" value="password" />
</bean>
来源:https://stackoverflow.com/questions/16531663/spring-data-mongodb-adding-credentials-for-mongodb-access