2

我有以下情况:

类 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 之前被调用,这样他还没有参数。我认为这会在 Service 类中生成一个 nullPointer。我如何接收字符串参数?

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

4

1 回答 1

1

真的是ServiceCaller配置的工作Service吗?如果是这样,那么这种情况并不适合依赖注入。就像现在一样创建Servicenew

ServiceCaller创建Service. 相反,您应该将参数直接注入Service到配置它,然后将配置Service注入到ServiceCaller.

现在,如果问题是参数来自ServiceCaller,但SomeClass需要注入,那么ServiceCallerGuice 和 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);
    }
}
于 2012-07-20T13:14:46.153 回答