Spring Data mongodb: adding credentials for MongoDb access

丶灬走出姿态 提交于 2019-12-09 19:12:36

问题


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.


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!