MongoDB
 sql >> Base de données >  >> NoSQL >> MongoDB

Comment utiliser Spring pour se connecter à MongoDB qui nécessite une authentification

trouvé la solution en utilisant Spring Expression Language

<bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate">
        <constructor-arg name="mongo" ref="mongo"/>
        <constructor-arg name="databaseName" value="${mongodb.dbname}"/>
        <constructor-arg name="userCredentials" ref="mongoCredentials"/>
    </bean>

    <bean id="mongoCredentials" class="org.springframework.data.authentication.UserCredentials">
        <property name="username" value="#{mongoURI.username}" />
        <property name="password" value="#{new java.lang.String(mongoURI.password)}" />
    </bean>

    <bean class="com.mongodb.MongoURI" id="mongoURI">
        <constructor-arg value="${mongodb.url}"  />
    </bean>

    <bean class="com.mongodb.Mongo" id="mongo">
        <constructor-arg ref="mongoURI" />
    </bean>