2016-10-23 4 views
2

私は先に作業した開発者から継承した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を持っている、と私getData()方法からClientFactory.getClientInstance()のようなものを呼び出し、クライアントの参照を持っていますが、Guiceのと、何でしょうそれを得るための正しい方法ですか?

PS。私はGuiceを学んでいるだけです。ありがとう!

答えて

3

すでにClientオブジェクトのプロバイダを持っているので、ここからは簡単です:

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

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

魔法のようなもの、右?

関連する問題