2014-03-12 56 views
1

Guice的新功能,所以我正在研究它的表現力。假設我有類如下:私人模塊和/或提供商的簡單使用

public class Data { 
    @Inject 
    public Data(@Named("First") String first, @Named("Second") String second) { ... } 
} 

public class DataUser1 { 
    @Inject 
    public DataUser1(Data data) { ... } 
} 

public class DataUser2 { 
    @Inject 
    public DataUser2(Data data) { ... } 
} 

如何創建一個模塊,這樣當我打電話injector.getInstance(DataUser1.class)同時具有injector.getInstance(DataUser2.class)我得到的東西相當於new DataUser2(new Data("foo2", "bar2"))我得到的東西相當於new DataUser1(new Data("foo", "bar"))

也相關,我如何創建一個模塊,我可能需要得到兩個實例DataUser1,其中每個使用不同的Data值?

回答

1

您可以使用private modules創建幾乎相同但具體細節不同的對象圖。

public class DataUser1Module extends PrivateModule { 
    @Override 
    protected void configure() { 
     bindConstant().annotatedWith(Names.named("First")).to("foo"); 
     bindConstant().annotatedWith(Names.named("Second")).to("bar"); 

     bind(Data.class); 
     bind(DataUser1.class); 

     expose(DataUser1.class); 
    } 
} 

public class DataUser2Module extends PrivateModule { 
    @Override 
    protected void configure() { 
     bindConstant().annotatedWith(Names.named("First")).to("foo2"); 
     bindConstant().annotatedWith(Names.named("Second")).to("bar2"); 

     bind(Data.class); 
     bind(DataUser2.class); 

     expose(DataUser2.class); 
    } 
} 

Injector injector = Guice.createInjector(new DataUser1Module(), new DataUser2Module()); 
DataUser1 dataUser1 = injector.getInstance(DataUser1.class); 
DataUser2 dataUser2 = injector.getInstance(DataUser2.class); 

你做同樣的事情,如果你需要用不同的Data S的DataUser1兩個實例,但你使用註釋來區分它們:

public class DataUser1Module1 extends PrivateModule { 
    @Override 
    protected void configure() { 
     bindConstant().annotatedWith(Names.named("First")).to("foo"); 
     bindConstant().annotatedWith(Names.named("Second")).to("bar"); 

     bind(Data.class); 
     bind(DataUser1.class).annotatedWith(Names.named("1")).to(DataUser1.class); 

     expose(DataUser1.class).annotatedWith(Names.named("1")); 
    } 
} 

public class DataUser1Module2 extends PrivateModule { 
    @Override 
    protected void configure() { 
     bindConstant().annotatedWith(Names.named("First")).to("foo2"); 
     bindConstant().annotatedWith(Names.named("Second")).to("bar2"); 

     bind(Data.class); 
     bind(DataUser1.class).annotatedWith(Names.named("2")).to(DataUser1.class); 

     expose(DataUser1.class).annotatedWith(Names.named("2")); 
    } 
} 

Injector injector = Guice.createInjector(new DataUser1Module1(), new DataUser1Module2()); 
DataUser1 dataUser11 = injector.getInstance(Key.get(DataUser1.class, Names.named("1")); 
DataUser1 dataUser12 = injector.getInstance(Key.get(DataUser1.class, Names.named("2")); 

這種模式是在吉斯FAQ described

參見下列問題: