Spring bean 到 google guice 转换

Spring bean to google guice conversion

以下片段摘自 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);
}

我自己解决了这个问题

提供程序 class 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);
        }
     }

创建了另一个 class 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);
        }

    }

然后在我们的注入中class我们可以简单地绑定这些提供者

    public class AppInjector extends AbstractModule {


        @Override
        protected void configure() {


            /*
             * JPA Bindings
             */
            bind(JPASearchProcessor.class).toProvider(JPASearchProcessorProvider.class);
            bind(MetadataUtil.class).toProvider(HibernateMetadataUtilProvider.class);


    }