以下代码段取自here。我的问题是我怎样才能在Guice中拥有这种约束力。
<bean id="searchProcessor" class="com.googlecode.genericdao.search.jpa.JPASearchProcessor">
<constructor-arg ref="metadataUtil" />
</bean>
<bean id="metadataUtil" class="com.googlecode.genericdao.search.jpa.hibernate.HibernateMetadataUtil"
factory-method="getInstanceForEntityManagerFactory">
<constructor-arg ref="entityManagerFactory" />
</bean>
我需要@Inject JPASearchProcessor(见下文)。我是Guice的新手。
@Inject
public void setSearchProcessor(JPASearchProcessor searchProcessor) {
super.setSearchProcessor(searchProcessor);
}
答案 0 :(得分:0)
我能够自己解决这个问题
创建提供程序类HibernateMetadataUtilProvider以提供HibernateMetadataUtil
package core.models.dao; import javax.persistence.EntityManagerFactory; import org.hibernate.ejb.HibernateEntityManagerFactory; import com.google.inject.Inject; import com.google.inject.Provider; import com.googlecode.genericdao.search.MetadataUtil; import com.googlecode.genericdao.search.jpa.hibernate.HibernateMetadataUtil; @SuppressWarnings("deprecation") public class HibernateMetadataUtilProvider implements Provider<MetadataUtil> { @Inject private EntityManagerFactory emf; @Override public MetadataUtil get() { return HibernateMetadataUtil.getInstanceForEntityManagerFactory((HibernateEntityManagerFactory) emf); } }
创建另一个类JPASearchProcessorProvider,它将注入JPASearchProcessor
package core.models.dao;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.googlecode.genericdao.search.MetadataUtil;
import com.googlecode.genericdao.search.jpa.JPASearchProcessor;
public class JPASearchProcessorProvider implements Provider<JPASearchProcessor> {
@Inject
private MetadataUtil mdu;
@Override
public JPASearchProcessor get() {
return new JPASearchProcessor(mdu);
}
}
然后在我们的注入类中,我们可以简单地绑定这些提供者
public class AppInjector extends AbstractModule { @Override protected void configure() { /* * JPA Bindings */ bind(JPASearchProcessor.class).toProvider(JPASearchProcessorProvider.class); bind(MetadataUtil.class).toProvider(HibernateMetadataUtilProvider.class); }