我正在尝试构建一些ConfigurationService来提供一些注入配置。我想使该属性之一在运行时变得易变。
我想实现这样的目标,但是我不知道如何在Guice中做到这一点。
指导模块:
public class ConfModule extends AbstractModule {
protected void configure() {
// how to bind class to itself, without any specific implementation
bind(Property1.class).to(Property1.class);
bind(IProperty2.class).to(Iproperty2DefaultImplementation1.class);
bind(IProperty2.class).annotatedWith(Names.named("setterOfproperty2").to( ? ? ? );
}
}
Conf类:
public class Conf {
@Inject // just consatant injected property1.class
private Property1 property1;
// variable property impl of interface
private IProperty2 property2;
// default impl of interface from module binding
@Inject
public Conf(IProperty2 property2) {
this.property2 = property2;
}
// method for changing implementation
@Inject
public setIProperty2(@Named("setterOfproperty2") IProperty2 property2) {
this.property2 = property2;
}
}
Conf服务类别:
public class ConfService {
@Inject
Conf configuration;
public Conf getConf() {
return configuration;
}
}
用法:
public static main() {
// return Conf with default IProperty2 impl
Injector injector = Guice.createInjector(new ConfModule());
ConfService c = injector.getInstance(ConfService.class);
// change to other Iproperty2Implementation
c.getConf().setIProperty2(new Iproperty2Implementation2());
}
有人想帮助我吗?