我有一个类有两个构造函数。我正在尝试使用 guice 工厂创建此类的实例。如果没有传递参数,则应调用默认构造函数。如果传递了参数,则应调用带参数的构造函数。但是目前即使我将参数传递给工厂方法,仍然会调用默认构造函数。带参数的构造函数根本没有被调用。下面是我的工厂类。
public interface MapperFactory {
PigBagMapper createPigBagMapper(@Assisted("pigMetaInfoList") List<String> sourceMetaInfoList);
JsonMapper createJsonMapper(@Assisted("apiName") String apiName) throws EndpointNotFoundException, JsonMapperException;
JsonMapper createJsonMapper();
}
下面是我要注入(inject)的构造函数。
@AssistedInject
public JsonMapper() {
handlers = new LinkedList<>();
}
@AssistedInject
public JsonMapper(@Assisted("apiName") String apiName) throws EndpointNotFoundException, JsonMapperException {
somelogic();
}
下面是我在抽象模块实现类中的模块绑定(bind)。
install(new FactoryModuleBuilder()
.implement(PigBagMapper.class, PigBagMapperImpl.class)
.implement(JsonMapper.class, JsonMapperImpl.class)
.build(MapperFactory.class));
下面是我调用构造函数的方式。
mapperFactory.createJsonMapper(apiName);
我在这里做错了什么?任何帮助将不胜感激。
编辑:
请注意 JsonMapperImpl 类没有构造函数。它只有一个公共(public)方法,仅此而已。
最佳答案
我看到两个问题。
问题 1:您不需要使用 @Assisted
注释工厂方法
问题 2:当您使用工厂时,Guice 将尝试创建一个 JsonMapperImpl
实例。它将扫描使用 @AssistedInject
注释的正确 JsonMapperImpl
构造函数。没有了。例如,您不能调用 new JsonMapperImpl("xyz")
。这将是一个编译时错误,因为 The constructor JsonMapperImpl(String) is undefined。
您也没有在 JsonMapperImpl
中使用 @AssistedInject
注释的构造函数。它是空的。
如果您以类似的方式重写您的类:
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
希望这对您有所帮助。
关于java - Guice 辅助注入(inject)多个构造函数总是调用默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41235020/