【问题标题】:How to inject service to hibernate.ejb.interceptor with google guice?如何使用 google guice 向 hibernate.ejb.interceptor 注入服务?
【发布时间】:2012-08-23 11:38:33
【问题描述】:

我在使用 google guice 向预定义拦截器注入服务时遇到问题。

我想要做的是使用emptyinterceptor 来拦截实体的更改。拦截器本身工作正常,问题是我不知道如何向它注入服务。注入本身在整个应用程序中都能正常工作。

persistence.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="db-manager">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>test.Address</class>
    <properties>
        <property name="hibernate.ejb.interceptor" value="customInterceptor"/>
    </properties>
</persistence-unit>

我如何尝试注入

public class CustomInterceptor extends EmptyInterceptor {

private static final Logger LOG = Logger.getLogger(CustomInterceptor.class);

@Inject
private Provider<UploadedFileService> uploadedFileService;
...
}

JpaPersistModule 是如何启动的

public class GuiceListener extends GuiceServletContextListener {

private static final Logger LOG = Logger.getLogger(GuiceListener.class);

@Override
protected Injector getInjector() {
    final ServicesModule servicesModule = new ServicesModule();
    return Guice.createInjector(new JerseyServletModule() {
        protected void configureServlets() {

            // db-manager is the persistence-unit name in persistence.xml
            JpaPersistModule jpa = new JpaPersistModule("db-manager");

                            ...
                    }
            }, new ServicesModule());
     }
}

如何启动服务

public class ServicesModule extends AbstractModule {

@Override
protected void configure() {
    bind(GenericService.class).to(GenericServiceImpl.class);
    bind(AddressService.class).to(AddressServiceImpl.class);
}
}

【问题讨论】:

    标签: jpa binding dependency-injection guice guice-persist


    【解决方案1】:

    我搜索了几个小时并没有找到真正的解决方案,所以我使用的丑陋解决方法是创建 2 个拦截器。

    第一个被hibernate正确绑定但没有注入任何东西。它通过其他机制调用第二个拦截器——在下面的示例中,通过对 InjectorFactory 的静态引用。第二个拦截器没有绑定到 Hibernate,但和其他任何类一样,它可以很高兴地将东西注入其中。

    //第一个ineterceptor有这样的方法...

    @Override
      public synchronized void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
      InjectorFactory.getInjector().getInstance(MyOtherInterceptor.class).onDelete(entity, id, state, propertyNames, types);
    }
    

    d

    //第二个有真正的实现

    @Inject
    public MyOtherInterceptor() {
    }
    
    @Override
    public synchronized void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
      //Full implementation
    }
    //etc
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多