This is my MongoClient Class that I want to inject into my Java EE Application. package org.sam.test;
import javax.annotation.PostConstruct;
import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType;
import javax.ejb.Lock;
import javax.ejb.LockType;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Named;
import javax.inject.Inject;
import com.mongodb.MongoClient;
@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
public class MongoConnectServer {
private MongoClient mongoClient = null;
public MongoConnectServer() {
String mongoIpAddress = "127.0.0.1";
Integer mongoPort = 27017;
try {
mongoClient = new MongoClient(mongoIpAddress, mongoPort);
} catch (Exception e) {
e.printStackTrace();
}
}
@Lock(LockType.READ)
public MongoClient getMongoClient(){
System.out.println(mongoClient);
return mongoClient;
}
public void setMongoClient(MongoClient mongoClient) {
this.mongoClient = mongoClient;
}
@PostConstruct
public void init() {
String mongoIpAddress = "127.0.0.1";
Integer mongoPort = 27017;
try {
mongoClient = new MongoClient(mongoIpAddress, mongoPort);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here is the main application, for some reason the mongoserver is giving me a null pointer exception and cannot figure out why it doesn't work, when I create an instance of MongoServer where the constructor passes the values then it works as shown in the lines below, any ideas how can I inject the Mongo Server, the post construct from MongoConnectServer to pass mongoclient doesn't seem to initialise the value, I am trying to avoid using new in the bean and want to inject the mongo class:
@Stateless
public class Test {
@EJB
static MongoConnectServer mongoserver;
public static void main(String[] args) {
/* Uncommenting this line below works */
//MongoConnectServer mongoserver = new MongoConnectServer();
System.out.println("App Start");
System.out.println(mongoserver);
MongoClient mongoClient = mongoserver.getMongoClient();
DB db = mongoClient.getDB("mydb");
DBCollection coll = db.getCollection("testCollection");
System.out.println(coll);
BasicDBObject doc = new BasicDBObject("name", "MongoDB")
.append("type", "database")
.append("count", 1)
.append("info", new BasicDBObject("x", 203).append("y", 102));
coll.insert(doc);
DBObject myDoc = coll.findOne();
System.out.println(myDoc);
}
}
Thanks for any responses
Aucun commentaire:
Enregistrer un commentaire