Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject a bean in this MongoDB connection case?

I have a class that has a MongoDB client member which is injected via constructor args:

public class MyDAO {

    private MongoClient mongoClient;

    public MyDAO(MongoClient mongoClient) {
        this.mongoClient = mongoClient;

        /*mongoClient = new MongoClient("localhost", 27017);*/   //This would be the way without using DI.

    }
}

My bean configuration file bean.xml is as follows:

<bean id="myDao" class="com.example.MyDAO">
        <constructor-arg ref="mongo" />
</bean>

<bean id="mongo" class="com.mongodb.MongoClient">
        <property name="host" value="localhost" />
        <property name="port" value=27017 />
</bean>

But I got the error message for the bean.xml as:

No setter found for property 'port' in class 'com.mongodb.MongoClient'

From MongoDB's Javadoc, the class MongoClient doesn't have setter methods for host and port properties. So how can I inject values into this Mongo bean?

like image 492
tonga Avatar asked Mar 23 '23 09:03

tonga


1 Answers

The MongoClient class seems to have a constructor

MongoClient(String host, int port)

you can therefore use constructor-based dependency injection

<bean id="mongo" class="com.mongodb.MongoClient">
    <constructor-arg name="host" value="localhost" />
    <constructor-arg name="port" value="27017" />
</bean>

Note: Because the parameter names are not always available (not through reflection, but through byte code manipulation), you can use the parameter type, which is always available, to distinguish

<bean id="mongo" class="com.mongodb.MongoClient">
    <constructor-arg type="java.lang.String" value="localhost" />
    <constructor-arg type="int" value="27017" />
</bean>
like image 152
Sotirios Delimanolis Avatar answered Apr 02 '23 05:04

Sotirios Delimanolis