在运行时更改 Guice 绑定
我希望能够在运行时更改 Guice 注入,以支持基于用户输入的多个注入。这就是我想实现的目标:
public interface IDao {
public int someMethod();
}
public class DaoEarth implements IDao {
@Override
public int someMethod(){ ... }
}
public class DaoMars implements IDao {
@Override
public int someMethod(){ ... }
}
public class MyClass {
@Inject
private IDao myDao;
public int myMethod(String domain) {
//If Domain == Earth, myDao should be of the type DaoEarth
//If Domain == DaoMars, myDao should be of the type DaoMars
}
}
我正在考虑编写自己的提供程序,但我不知道如何使用该提供程序在运行时更改我的绑定。任何意见都受到欢迎,并:)赞赏!
更新这是我目前想出的,它并不像我想要的那么漂亮,所以我仍然在寻找反馈
public class DomainProvider {
@Inject @Earth
private IDaoProvider earthDaoProvider;
@Inject @Mars
private IDaoProvider marsDaoProvider;
public IDaoProvider get(Domain domain){
switch (domain){
case EARTH:
return earthDaoProvider;
case MARS:
return marsDaoProvider;
}
}
public IDaoProvider get(String domain){
Domain parsedDomain = Domain.valueOf(domain.toUpperCase());
return get(parsedDomain);
}
}
//MarsDaoProvider would be equivalent
public class EarthDaoProvider implements IDaoProvider {
@Inject @Earth
private IDao earthDao;
public IDao getDao() {
return earthDao;
}
}
// This means that in "MyClass", I can do:
public class MyClass {
@Inject
private DomainProvider domainProvider;
public int myMethod(String domain) {
IDaoProvider daoProvider = domainProvider.get(domain);
IDao dao = daoProvider.getDao();
//Now "dao" will be of the correct type based on the domain
}
}
//Of course elsewhere I have the bindings set like
bind(IDao.class).annotatedWith(Earth.class).to(EarthDao.class);