MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Come utilizzare Spring per connettersi a MongoDB che richiede l'autenticazione

trovato la soluzione usando 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>