Create multiple instances of class using guice
There is a class that holds some state and implements an interface. This class should be registered multiple times at a GUICE module with different configurations. The class has dependencies to other beans, which should be injected by GUICE. Example:
public class MenuItemImpl implements MenuItem {
@Inject
AnyService service;
public MenuItemImpl(String caption) {
this.caption = caption;
}
//...
}
Instead of using a c'tor parameter a public setter is possible, too.
In the Guice module I want to bind multiple instances of the MenuItemImpl class.
I tried to use a Provider<T>
, however, dependent beans are not injected in this case.
Multibinder<MenuItem> binder = Multibinder.newSetBinder(binder(), MenuItem.class);
binder.addBinding().toProvider( new Provider<MenuItem>() {
@Override
public MenuItem get() {
return new MenuItemImpl("StartCaption");
}
}
I took a look at @Assist annotiation. However, I want to specify the configuration during binding phase in module and not when consuming the bean.
The only workaround I see is creating different subclasses for every configuration which is bad style imho and not what is OO is intended to be.
public class A
{
@Inject
@Named("startCaption")
private MenuItem menuItem;
}
public class B
{
@Inject
@Named("endCaption")
private MenuItem menuItem;
}
和Guice模块
String[] captions = { "startCaption", "endCaption" };
for(final String caption : captions)
{
bind(MenuItem.class).annotatedWith(Names.named(caption)).toProvider(
new Provider<MenuItem>()
{
public MenuItem get()
{
return new MenuItemImpl(caption);
}
});
}
链接地址: http://www.djcxy.com/p/94648.html
上一篇: Guice自定义注入构造函数参数
下一篇: 使用guice创建类的多个实例