2

下面的代码片段取自这里。我的问题是如何在 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);
}
4

1 回答 1

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);


    }

于 2015-11-12T06:08:34.393 回答