如何使用google guice向hibernate.ejb.interceptor注入服务?

时间:2012-08-23 11:38:34

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

我遇到使用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);
}
}

1 个答案:

答案 0 :(得分:3)

我搜索了几个小时并找不到真正的解决方案,所以我使用的丑陋的解决方法是创建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