(或者可能用法不正确?我是Guice的新手)我会犯以下错误:
我有以下几点:
public interface BaseRepository<T, PK> (){
public void f1();
}
public class BaseRepositoryMongoImpl<T, String> extends BaseDAO<T, String> implements BaseRepository<T, String> {
@Inject
BaseRepositoryMongoImpl(MongoClient mongoClient, Morphia morphia,
String dbName, @Assisted Class<T> type) {
super(type, mongoClient, morphia, (java.lang.String) dbName);
}
public void f1(){}
}工厂接口和类
public interface BaseRepositoryFactory {
public BaseRepository create(Class<?> tableClass);
}
public class BaseRepositoryFactoryImpl implements BaseRepositoryFactory {
private final MongoClientProvider mongoClientProvider;
private final MorphiaProvider morphiaProvider;
@Inject
public BaseRepositoryFactoryImpl(MongoClientProvider mongoClientProvider,
MorphiaProvider morphiaProvider) {
this.mongoClientProvider = mongoClientProvider;
this.morphiaProvider = morphiaProvider;
}
@Override
public BaseRepository create(Class<?> tableClass) {
return new BaseRepositoryMongoDBImpl(mongoClientProvider.get(),
morphiaProvider.get(),
"DATABASE_NAME", //comes from properties
tableClass);
}
}提供程序类
public class MongoClientProvider implements Provider<MongoClient> {
@Override
public MongoClient get() {
MongoClient mongoClient = null;
try {
//for sake of simplicity, all properties code is removed
//the database name is part of the properties
mongoClient = new MongoClient("DATABASE_HOST");
} catch (UnknownHostException ex) {
Logger.error("Severe Error: Unknown database host", ex);
}
return mongoClient;
}
}
public class MorphiaProvider implements Provider<Morphia> {
@Override
public Morphia get() {
Morphia morphia = new Morphia();
//for sake of simplicity, all properties code is removed
//the package name is part of the properties
morphia.mapPackage("MODEL_PACKAGE", true);
return morphia;
}
}最后,模块类
public class DatabaseModule extends AbstractModule {
@Override
protected void configure() {
install(new FactoryModuleBuilder()
.implement(BaseRepository.class, BaseRepositoryMongoDBImpl.class)
.build(BaseRepositoryFactory.class));
}
}我需要在模块类中使用TypeLiteral吗?
另外,我是否可以将BaseRepositoryFactory变量声明为
@Inject
private static BaseRepositoryFactory baseRepo;提前感谢!
发布于 2015-02-15 14:22:27
First:不能注入普通字符串的,guice只是不知道要注入什么。使用限定符指定所需的内容。最简单的修饰符:@Named。
所以:
@Inject
@Named("foo")
private String myString;
@Provides
@Named("foo")
public String myString() {
return ... whatever myString should be ... constant? property? DB value?
}第二种:您的辅助注射方法不是“骗人的”方法。查看辅助注射延伸,您不必自己实现接口:
install(new FactoryModuleBuilder()
.implement(Payment.class, RealPayment.class)
.build(PaymentFactory.class));这样,您就可以摆脱一些代码,这样搜索真正的问题就容易多了。
第三:您可以使用requestStaticInjection(),但通常不应该这样做。依赖注入和静态值持有者的概念不匹配,您会遇到很多麻烦,只需使用单例绑定即可。
https://stackoverflow.com/questions/28509608
复制相似问题