使用Guice创建并初始化单例

时间:2015-06-22 18:48:11

标签: java guice

我有以下课程 StorageProxy.java(接口) StorageProxyImpl1.java(StorageProxy接口的Implementation1)

public class StorageProxyImpl1 extends StorageProxy{
    public void init(String key){
      ....
    }
}

public class Resource1{
    private StorageProxy sp;
    ...
}

public class Resource2{
    private StorageProxy sp;
    ...
}

我在Application类中有一个main方法,用于初始化和使用Resource1和Resource2。

public class MyApp{
  public static void main(String args[]){
    Resource1 r1 = new Resource1();
    Resource2 r2 = new Resource2();
    runApp(r1,r2);
  }
  public void runApp(Resource1 r1, Resource2 r2){ // Makes use of r1 and r2
    ...
  }
}

我想知道StorageProxy的依赖注入,以便在创建新实现时没有太多的痛苦。我希望Resource1和Resource2使用StorageProxy的相同对象(即它应该是Singleton)。 init与构造函数是分开的,这一点至关重要。总结一下,我需要在main方法中创建一个StorageProxyImpl1实例并在其上调用StorageProxyImpl1.init(String),这个实例应该由Resource1和Resource2共享。怎么做?

Guice: How to get instance of Singleton without injector or using Constructor Injection中提出的问题在高层次上有点问题,如果没有具体的例子,我觉得很难理解。

1 个答案:

答案 0 :(得分:-1)

您可以使用provider interface

public class StorageProxyProvider implements Provider<StorageProxy> {
   public StorageProxy get() {
      StorageProxy storageProxy = new StorageProxy();
      storageProxy.init();
      return storageProxy;
   }
}

public class StorageProxyModule extends AbstractModule {
   protected void configure() {
     bind(StorageProxy.class).toProvider(StorageProxyProvider.class).in(Singleton.class);
   }
}

一个工作示例:

public class StorageProxyProvider implements Provider<StorageProxy> {

    public StorageProxy get() {
        StorageProxy storageProxy = new StorageProxy();
        storageProxy.init();
        return storageProxy;
    }

}


public class StorageProxy {

    public void init(){
        System.out.println("init");
    }
    public void proxy(){
        System.out.println("proxy");
    }

}

public class StorageProxyModule extends AbstractModule {
    protected void configure() {
        bind(StorageProxy.class).toProvider(StorageProxyProvider.class).in(Singleton.class);
    }
}


public class Example {
    @Inject
    StorageProxy storageProxy;

    public void doSomethingThatNeedStorageProxy() {
        System.out.println(storageProxy);
        storageProxy.proxy();
    }

}

public class Main {
    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new StorageProxyModule());
        Example e = injector.getInstance(Example.class);
        e.doSomethingThatNeedStorageProxy();
        e = injector.getInstance(Example.class);
        e.doSomethingThatNeedStorageProxy();
    }
}