2

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

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

持久性.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);
}
}
4

1 回答 1

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
于 2014-08-13T09:06:37.447 回答