Reputation: 3261
I am trying to develop rest code using spring.
@RestController
public class MongoController {
@Autowired
private MongoDAO mongoDAO ;
@RequestMapping(value = "/mongotest", method = RequestMethod.GET)
public String creatTest() {
return " YO Mongo";
}
}
And my MongoDAO class looks like below
@Service("mongoDAO")
@Component
public class MongoDAO {
@Resource
private DBCollection user ;
@Resource
private MongoDatabase userDatabase;
@Resource
private MongoCollection<Document> usersCollection;
@Resource
private MongoClient mongoClient;
/* public MongoDAO(final MongoDatabase userDatabase) {
usersCollection = userDatabase.getCollection("user");
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB("ITAU");
user = db.getCollection("user");
}*/
public MongoDAO(MongoDatabase userDatabase1) {
usersCollection = userDatabase1.getCollection("user");
}
public MongoDAO() {
usersCollection = userDatabase.getCollection("user");
}
But the error I am getting is ..
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDAO' defined in file [C:\Users\user\Desktop\ITAU\77\ABC-iCOE-WAL\ItauBankingTransac s\rest-client\target\classes\com\ABC\WAL\itaudemo\mongo\dao\MongoDAO.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could n nstantiate bean class [com.ABC.WAL.itaudemo.mongo.dao.MongoDAO]: Constructor threw exception; nested exception is java.lang.NullPointerException at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1076)
Upvotes: 0
Views: 2699
Reputation: 3422
The field userDatabase
is autowired after creating MongoDao
bean. If you want to perform some after constructing actions try this:
@Service("mongoDAO")
public class MongoDAO {
@Resource
private DBCollection user ;
@Resource
private MongoDatabase userDatabase;
@Resource
private MongoCollection<Document> usersCollection;
@Resource
private MongoClient mongoClient;
public MongoDAO() {
}
@PostConstruct
public postConstruct() {
usersCollection = userDatabase.getCollection("user");
}
The constructor might be omitted. Generally it is better not to have custom constructors for component classes.
Upvotes: 3
Reputation: 4506
Just use @Service("mongoDAO")
no need of @Component
@Service("mongoDAO")
public class MongoDAO {
You can use either of the two annotations, @Service is used in service layer code for readability. @Component is more of a generic annotation.
Upvotes: 1