如何使用谷歌指南将服务注入hibernate.ejb.interceptor



我遇到了一个问题,使用谷歌指南将服务注入预定义的拦截器。

我要做的是使用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);
}
}

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

最新更新