我不明白你为什么需要它,但如果你真的想要,这是可能的:
package stackoverflow;
import javax.inject.Inject;
import javax.inject.Singleton;
import junit.framework.Assert;
import org.junit.Test;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
public class InjectorSingletonTest {
static class ModuleOne extends AbstractModule {
@Override
protected void configure() {
bind(MySingleton.class);
}
}
static class ModuleTwo extends AbstractModule {
final MySingleton singleton;
@Inject
ModuleTwo(MySingleton singleton){
this.singleton = singleton;
}
@Override
protected void configure() {
bind(MySingleton.class).toInstance(singleton);
}
}
@Singleton
static class MySingleton { }
@Test
public void test(){
Injector injectorOne = Guice.createInjector(new ModuleOne());
Module moduleTwo = injectorOne.getInstance(ModuleTwo.class);
Injector injectorTwo = Guice.createInjector(moduleTwo);
MySingleton singletonFromInjectorOne =
injectorOne.getInstance(MySingleton.class);
MySingleton singletonFromInjectorTwo =
injectorTwo.getInstance(MySingleton.class);
Assert.assertSame(singletonFromInjectorOne, singletonFromInjectorTwo);
}
}