【发布时间】:2014-07-26 21:21:59
【问题描述】:
我希望能够在运行时更改 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);
【问题讨论】:
-
我不确定辅助注射对我有什么帮助。我知道辅助注入允许您将注入的参数与提供的参数结合起来,但我不确定这将如何适用于我的情况。
标签: java architecture dependency-injection playframework-2.0 guice