我有一个简单的问题。是否可以通过@Ressource或@Autowired向Hibernate Eventlistener添加依赖项注入?
我将向您展示我的entitymanagerfactory配置:
<bean id="entityManagerFactory" class="org.hibernate.ejb.EntityManagerFactoryImpl"> <qualifier value="entityManagerFactory" /> <constructor-arg> <bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="persistenceUnitManager"> <bean class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManagerr"> <property name="defaultDataSource" ref="dataSource" /> </bean> </property> <property name="dataSource" ref="dataSource" /> <property name="persistenceUnitName" value="mis" /> <property name="persistenceProviderClass" value="org.hibernate.ejb.HibernatePersistence" /> <property name="jpaProperties" ref="jpa.properties" /> <property name="jpaDialect" ref="jpaDialect" /> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="generateDdl" value="true" /> <property name="database"> <util:constant static-field="org.springframework.orm.jpa.vendor.Database.POSTGRESQL" /> </property> <property name="showSql" value="true" /> </bean> </property> </bean> </constructor-arg> </bean>
目前,我通过jpa.properties注册了我的监听器,
hibernate.ejb.event.load=com.example.hibernate.events.LoadEvent
但是在这种情况下,我的听众没有弹簧注入。我找到了一个解决方案,但是它使用了sessionFactory而不是objectmanager oder我可以在我的上下文中修改sessionfactory吗?希望有人有一个好主意或解决方案如何解决这个问题!
太谢谢了!
如果您使用SessionFactory,则将是以下配置:
<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- Stripped other stuff --> <property name="eventListeners"> <map> <entry key="pre-load"> <bean class="com.mycompany.MyCustomHibernateEventListener1" /> </entry> <entry key="pre-persist"> <bean class="com.mycompany.MyCustomHibernateEventListener2" /> </entry> </map> </property> </bean>
但是由于您使用的是JPA,因此恐怕您需要使用此线程中概述的AOP
或者你可以
基类:
public abstract class ListenerBase{ protected void wireMe(){ ApplicationContext ctx = ContextHelper.getCurrentApplicationContext(); ctx.getAutowireCapableBeanFactory().autowireBean(this); } }
现在在您的lifycycle方法中wireMe()先调用。
wireMe()
更新:
这是一个示例实现ContextHelper:
ContextHelper
public final class ContextHelper implements ApplicationContextAware{ private static final ContextHelper INSTANCE = new ContextHelper(); private ApplicationContext applicationContext; @Override public void setApplicationContext(final ApplicationContext applicationContext){ this.applicationContext = applicationContext; } public static ApplicationContext getCurrentApplicationContext(){ return INSTANCE.applicationContext; }; public static ContextHelper getInstance(){ return INSTANCE; } private ContextHelper(){ } }
将其连接到您的Spring Bean配置中,如下所示:
<bean class="com.mycompany.ContextHelper" factory-method="getInstance" />