1

我有一个有两个构造函数的类。我正在尝试使用 guice 工厂创建此类的实例。如果没有传递参数,则应调用默认构造函数。如果传递了参数,则应调用带参数的构造函数。但是目前即使我将参数传递给工厂方法,仍然会调用默认构造函数。带参数的构造函数根本没有被调用。下面是我的工厂课。

public interface MapperFactory {

PigBagMapper createPigBagMapper(@Assisted("pigMetaInfoList") List<String> sourceMetaInfoList);

JsonMapper createJsonMapper(@Assisted("apiName") String apiName) throws EndpointNotFoundException, JsonMapperException;

JsonMapper createJsonMapper();

}

下面是我试图注入的构造函数。

@AssistedInject
public JsonMapper() {
    handlers = new LinkedList<>();
}

 @AssistedInject
 public JsonMapper(@Assisted("apiName") String apiName) throws EndpointNotFoundException, JsonMapperException {
    somelogic();
}

下面是我在抽象模块实现类中的模块绑定。

install(new FactoryModuleBuilder()
            .implement(PigBagMapper.class, PigBagMapperImpl.class)
            .implement(JsonMapper.class, JsonMapperImpl.class)
            .build(MapperFactory.class));

下面是我如何调用构造函数。

mapperFactory.createJsonMapper(apiName);

我在这里做错了什么?任何帮助将非常感激。

编辑:

请注意,JsonMapperImpl 类没有构造函数。它只有一个公共方法,仅此而已。

4

1 回答 1

5

我看到两个问题。

问题 1:您不需要使用注释工厂方法@Assisted

问题 2: Guice 将尝试创建JsonMapperImpl您何时使用工厂的实例。它将扫描JsonMapperImpl带有注释的适当构造函数@AssistedInject。没有了。例如,您不能调用new JsonMapperImpl("xyz")。这将是一个编译时错误,因为构造函数 JsonMapperImpl(String) 是 undefined

您也没有使用@AssistedInjectin注释的构造函数JsonMapperImpl。它是空的。

如果您以类似的方式重写您的课程:

public class JsonMapperImpl extends JsonMapper
{
    @AssistedInject
    public JsonMapperImpl() {
        super();
    }

     @AssistedInject
     public JsonMapperImpl(@Assisted String apiName) {
         super(apiName);
    }
}

和:

public class JsonMapper
{
    private String apiName;

    public JsonMapper() {

    }

     public JsonMapper(String apiName) {
         this.apiName = apiName;
    }

    public String getAPI(){return apiName;}
}

然后JsonMapperImpl将公开适当的构造函数并且代码将起作用,例如:

JsonMapper noApi = factory.createJsonMapper();
JsonMapper api = factory.createJsonMapper("test");

System.out.println(noApi.getAPI());
System.out.println(api.getAPI());

输出:

null
test

希望这可以帮助。

于 2016-12-21T10:46:35.500 回答