无法在 Spring 中初始化 bean class

Could not initialize bean class in Spring

我正在尝试使用 spring 开发剩余代码。

@RestController
public class MongoController {

    @Autowired
    private MongoDAO mongoDAO ;

    @RequestMapping(value = "/mongotest", method = RequestMethod.GET)
    public String creatTest() {

        return " YO Mongo";
    }


}  

我的 MongoDAO class 如下所示

@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");

    }

但是我得到的错误是..

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDAO' defined in file [C:\Users\user\Desktop\ITAU\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)

只用@Service("mongoDAO")不需要@Component

@Service("mongoDAO")
public class MongoDAO {

两种注解都可以使用,服务层代码中使用@Service是为了提高可读性。 @Component 更像是一个通用注解。

字段 userDatabase 在创建 MongoDao bean 后自动装配。如果你想在构造动作后执行一些,试试这个:

@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");

    }

构造函数可能会被省略。一般来说,组件 类.

最好不要有自定义构造函数