java - 无法在 Spring 中初始化 bean 类

标签 java spring spring-mvc spring-boot spring-data

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

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

    }

但是我收到的错误是..

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)

最佳答案

字段userDatabase在创建MongoDao bean后 Autowiring 。如果您想在构建操作后执行一些操作,请尝试以下操作:

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

    }

构造函数可以被省略。一般来说,组件类最好不要有自定义构造函数。

关于java - 无法在 Spring 中初始化 bean 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31313510/

相关文章:

java - 选择正确的数据结构

java - 获取特定用户的所有权限

java - org.hibernate.MappingException : Unknown entity on User object that contains Entity annotation

spring - 如何定义重试次数不应该尝试使用 hystrix

java - 在spring配置中创建具有不同属性值的类的多个bean实例

java - 找到了多个名为 [spring_web] 的片段。在非maven项目中

Java泛型方法声明基础

java - Spring组件中如何访问HttpServletResponse?

java - 如何将 java java.nio.ByteBuffer 转换为 spring org.springframework.web.multipart.MultipartFile?

Java Spring MVC - 模型中类的动态属性名称