How to use Spring to connect to MongoDB which requires authentication

mongodb, spring

Solution

found the solution using 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>

Problem

I am using the below Spring configuration in order to connect to mongoDB ``` <bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate"> <constructor-arg name="mongo" ref="mongo"/> <constructor-arg name="databaseName" value="${mongodb.dbname}"/> </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> ``` where `mongo.url=mongodb://<user>:<password>@<host>:27017` However I'm getting an authetication error. My understanding was that MongoUI can take a URL in the above format. I know that mongoTemplate can accept userCredentials object however I would need to extract them from the URL first and i'm not sure how to do that in the configuration. Any idea how can I change my config above to suppot this assuming mongo.url format cannot be changed?

Original source