我正在尝试使用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:\用户\用户\桌面\ ITAU \ 77 \ ABC-iCOE-WAL \ ItauBankingTransac s \ rest-client \ target \ classes \ com \ ABC \ WAL \ itaudemo \ mongo \ dao \ MongoDAO.class]:bean的实例化失败;嵌套异常是 org.springframework.beans.BeanInstantiationException:可以吗? nstantiate bean class [com.ABC.WAL.itaudemo.mongo.dao.MongoDAO]: 构造函数抛出异常;嵌套异常是 显示java.lang.NullPointerException 在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1076)
答案 0 :(得分:3)
创建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");
}
可能会省略构造函数。通常,最好不要为组件类定制构造函数。
答案 1 :(得分:1)
只需使用@Service("mongoDAO")
,无需@Component
@Service("mongoDAO")
public class MongoDAO {
您可以使用两个注释中的任何一个,@ Service用于服务层代码以提高可读性。 @Component更像是一个通用的注释。