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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With