Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data mongodb: adding credentials for MongoDb access

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.

like image 237
pastafarian Avatar asked Feb 23 '26 23:02

pastafarian


1 Answers

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>
like image 108
Bhushan Bhangale Avatar answered Feb 26 '26 16:02

Bhushan Bhangale



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!