我正在尝试使用spring开发rest代码。
@RestController
public class MongoController {
@Autowired
private MongoDAO mongoDAO ;
@RequestMapping(value = "/mongotest", method = RequestMethod.GET)
public String creatTest() {
return " YO Mongo";
}
}
我的MongoDAO课程如下
@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");
}
但是我得到的错误是..
引起原因:org.springframework.beans.factory.BeanCreationException:
在文件中定义名称为“ mongoDAO”的bean时出错
[C:\ Users \ user \ Desktop \ ITAU \ 77 \ ABC-iCOE-WAL \ ItauBankingTransac
s \ rest-client \ target \ classes \ com \ ABC \ WAL \ itaudemo \ mongo \ dao \ MongoDAO.class]:实例化Bean失败;嵌套异常为
org.springframework.beans.BeanInstantiationException:是否可以
实例化bean类[com.ABC.WAL.itaudemo.mongo.dao.MongoDAO]:
构造函数抛出异常;嵌套异常为
java.lang.NullPointerException
在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1076)
最佳答案
创建userDatabase
bean之后,将自动连接MongoDao
字段。如果要在构造动作后执行一些操作,请尝试以下操作:
@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");
}
构造函数可以省略。通常,最好不要为组件类提供自定义构造函数。