从Guice模块调用方法?

时间:2016-10-23 00:01:57

标签: java guice

所以我需要处理一个Guice项目,该项目是我从早期开发过它的开发人员那里继承的,我有一个特定的问题要解决。 让我简要介绍一下应用程序设计。

MyService.java

public static void main(String[] args) {

    Injector injector = createInjector(new MyModule());
}

MyModule.java

// ...

@Inject
@Provides
@Singleton
public Client getClient(@Named("config") String config) {
    // Client should be singleton
    return new Client(config); 
} 

现在问题是我必须编写使用Client的服务操作,该操作在应用程序的某个地方作为单例存在,但我不知道什么是获得的好方法它。我需要以下内容。

ServiceOperations.java

// ...

public String getData() {
    // somehow obtain that client - how?
    // and then call operations on the client
    return client.getData();
}

如果它不是Guice,我只会有一个ClientFactory,并从我的ClientFactory.getClientInstance()方法调用类似getData()的内容并拥有客户端引用,但是使用Guice,获得它的正确方法是什么?

PS。我只是在学习Guice。谢谢!

1 个答案:

答案 0 :(得分:3)

由于您已经拥有Client对象的提供程序,因此从这里可以直截了当:

class ServiceOperations {
    @Inject
    public ServiceOperations(Client client) {
        this.client = client;
    }

    public String getData() {
        return client.getData();
    }
}

神奇的东西,对吧?