使用自动装配的组件获取NullPointerException

时间:2018-04-16 16:48:45

标签: java spring-boot

以下是我尝试自动装配的课程:

package com.myproject.propdrone.lib;

import com.mongodb.MongoClient;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;
import org.mongodb.morphia.mapping.MapperOptions;
import org.springframework.stereotype.Component;

@Component
class MongoDriver {
    private final Morphia morphia;
    private final Datastore datastore;

    MongoDriver() {
        morphia = new Morphia();
        datastore = morphia.createDatastore(new MongoClient(), "propdrone");
        MapperOptions options = morphia.getMapper().getOptions();
        options.setStoreEmpties(true);
        options.setStoreNulls(true);
        morphia.mapPackage("com.myproject.propdrone.models");
        datastore.ensureIndexes();
    }

    Datastore getDatastore() {
        return datastore;
    }
}

这是我自动装配它的课程:

package com.myproject.propdrone.lib;
//other imports here
@Component
public class BuildingDataDAO {
    @Autowired
    private MongoDriver mongoDriver;
    private Datastore datastore;
    private List<BuildingData> allBuildingData;

    public BuildingDataDAO() {
        datastore = mongoDriver.getDatastore(); // THIS FAILS
        allBuildingData = getAllBuildingData();
    }
    // other class definitions

我正在为mongoDriver变量抛出NullPointerException

主应用程序类位于包com.myproject中,并使用@SpringBootApplication进行注释,因此它应自动扫描这些组件。但我不明白为什么会失败。

修改 我修改了BuildingDataDTO以使用@PostConstruct,但我仍然面临这个问题:

@PostConstruct
    private void initDatastore() {
        datastore = mongoDriver.getDatastore();
    }

在另一个类中,我通常将BuildingDataDTO实例化为:

private final BuildingDataDAO buildingDataDAO = new BuildingDataDAO();

当在使用数据存储区的 buildingDataDAO 上调用方法时,我得到 NullPointerException

2 个答案:

答案 0 :(得分:0)

两个问题: 1.禁用SpringBoot的自动配置示例:

@SpringBootApplication(exclude={MongoAutoConfiguration.class,   MongoDataAutoConfiguration.class})
    public class TestMorphiaApplication {

        public static void main(String[] args) {
            SpringApplication.run(TestMorphiaApplication.class, args);
        }
    }
  1. 以下内容适用于您的示例

    @Component 公共类BuildingDataDAO {     @Autowired     私人MongoDriver mongoDriver;     私有数据存储区数据存储区;

    public BuildingDataDAO() {
    }
    
    @PostConstruct
    private void init() {
      datastore = mongoDriver.getDatastore();
    }
    

    }

答案 1 :(得分:-2)

您从未初始化mongoDriver对象。

添加:

mongoDriver = new MongoDriver();