How to insert a bean in this MongoDB connection case?

I have a class that has a MongoDB client member that is introduced through the args constructor:

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 an error for bean.xml as:

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

From MongoDB Javadoc , the MongoClient class MongoClient not have setter methods for the host and port properties. So how can I embed values ​​in this Mongo bean?

+4
source share
2 answers

The MongoClient class has a constructor

 MongoClient(String host, int port) 

you can use constructor-based dependency nesting

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

Note. Since parameter names are not always accessible (not through reflection, but through manipulation of byte code), you can use the parameter type, which is always available to distinguish between

 <bean id="mongo" class="com.mongodb.MongoClient"> <constructor-arg type="java.lang.String" value="localhost" /> <constructor-arg type="int" value="27017" /> </bean> 
+5
source

Since the MongoClient class MongoClient not have setters for port and host , but supports passing host and port values ​​in the constructor, you can switch property to constructor-arg .

 <bean id="mongo" class="com.mongodb.MongoClient"> <constructor-arg name="host" type="java.lang.String" value="localhost" /> <constructor-arg name="port" type="java.lang.Integer" value="27017" /> </bean> 
+2
source

Source: https://habr.com/ru/post/1502628/


All Articles