创建单例实例时,构造函数未定义

时间:2018-06-01 07:03:19

标签: java

我的班级ProductDao中有一个参数化构造函数,我必须创建单例实例,但无法创建它。

抛出“构造函数ProductDao()未定义”错误。

请在下面找到我的代码。

private static ProductDao instance = new ProductDao();

public static ProductDao getInstance() {
    return instance;
}

private RestHighLevelClient restHighLevelClient;

private ObjectMapper objectMapper;

public ProductDao( ObjectMapper objectMapper, RestHighLevelClient restHighLevelClient) {
    this.objectMapper = objectMapper;
    this.restHighLevelClient = restHighLevelClient;
}

3 个答案:

答案 0 :(得分:1)

编译器自动为没有构造函数的任何类提供无参数的默认构造函数。但是,当您指定一个默认构造函数时,它不会提供任何默认构造函数。在你的情况下,你有一个。

public ProductDao( ObjectMapper objectMapper, RestHighLevelClient restHighLevelClient) {
    this.objectMapper = objectMapper;
    this.restHighLevelClient = restHighLevelClient;
}

您需要提供默认构造函数

    public ProductDao() {
            // If you have default singleton beans for your mapper and client. 
//Use it to call the parameterized constructor.

        }

答案 1 :(得分:1)

如果您想要空构造函数,请将其写入构造函数:

public ProductDao( ) {
    this.objectMapper = new ObjectMapper;
    this.restHighLevelClient = new RestHighLevelClient;
}

public ProductDao( ObjectMapper objectMapper, RestHighLevelClient restHighLevelClient) {
    this.objectMapper = objectMapper;
    this.restHighLevelClient = restHighLevelClient;
}

答案 2 :(得分:1)

只需实现缺少的构造函数,使其成为private以及重载的构造函数,并实现相应的getInstance方法以获得真正的单例。如果您将构造函数设为公共,那么很可能会在JVM周围运行多个实例!

class ProductDao {
    private static ProductDao instance;

    public static ProductDao getInstance() {
        if (instance == null) {
            instance = new ProductDao();
        }
        return instance;
    }

    // this is the parametrized getInstance method
    public static ProductDao getInstance(ObjectMapper objectMapper, RestHighLevelClient restHighLevelClient) {
        if (instance == null) {
            instance = new ProductDao(objectMapper, restHighLevelClient);
        } else {
            instance.objectMapper = objectMapper;
            instance.restHighLevelClient = restHighLevelClient;
        }
        return instance;
    }

    private static RestHighLevelClient restHighLevelClient;

    private static ObjectMapper objectMapper;

    // this is what you need
    private ProductDao() {}

    // this has to be private
    private ProductDao( ObjectMapper objectMapper, RestHighLevelClient restHighLevelClient) {
        this.objectMapper = objectMapper;
        this.restHighLevelClient = restHighLevelClient;
    }
}