我有以下情况:

类ServiceCaller:

public class ServiceCaller{
    private Service service;
    public void initialize(List<String> params){
        //get the params from list and set to String objects
        service = new Service(param1,param2);
    }
}


班级服务:

public class Service{
    SomeClass classe;
    public Service(String param1,String param2){
        //call methods to do stuffs with params
        classe = new SomeClass();
    }
}


我的应用程序有一个框架,该框架在构造后读取.properties并调用ServiceCaller类,并初始化并填充ServiceCaller中的参数。
Service类仅使用参数,并实例化SomeClass类。

我试图将所有这些传递给Google Guice,而我的课程是如此:

班级服务呼叫者:

public class ServiceCaller{
    private final Service service;

    @Inject
    public ServiceCaller(Service service){
        this.service = service;
    }
    public initialize(List<String> params){
        //set params to objects...
    }
}


和班级服务:

public class Service{
    private final SomeClass classe;

    @Inject
    public Service(SomeClass classe, String param1,String param2){
        //call methods to do stuffs with params
        this.classe = classe;
    }
}


我的疑问是:我该怎么做?

1-在ServiceCaller中,在initMethod之前称为注入的构造函数,这样他就没有Params了。我认为这会在Service类中生成nullPointer。我如何接收String参数?

2-如何在ServiceCaller类内部注入服务类?他需要调用init,使用参数挂载Service类,并且仅在此刻将Service(已经带有参数)注入ServiceCaller。

最佳答案

配置ServiceCaller真的是Service的工作吗?如果是这样,那么这种情况实际上不适合依赖注入。像现在一样使用Service创建new

但是创建ServiceCaller可能不是Service的工作。而是,应将参数直接注入到Service中进行配置,然后将已配置的Service注入到ServiceCaller中。

现在,如果问题在于参数来自ServiceCaller,但是需要注入SomeClass,则ServiceCaller和Guice都将无法自行完成工作。我建议您拆分构造:创建一个ServiceFactory,可以将其注入SomeClass,然后注入ServiceCaller,然后提供一种采用参数的工厂方法。就像是:

ServiceCaller {
    private final ServiceFactory serviceFactory;
    private Service service;

    @Inject
    public ServiceCaller(ServiceFactory serviceFactory) {
        this.serviceFactory = serviceFactory;
    }

    public void initialize(List<String> params) {
        service = serviceFactory.create(params.get(0), params.get(1));
    }
}

class Service {
    private final SomeClass classe;

    public Service(SomeClass classe, String param1, String param2) {
        //call methods to do stuffs with params
        this.classe = classe;
    }
}

class ServiceFactory {
    private final SomeClass classe;

    @Inject
    public ServiceFactory(SomeClass classe) {
        this.classe = classe;
    }

    public Service create(String param1, String param2) {
        return new Service(classe, param1, param2);
    }
}

09-27 15:22