Spring + EntityManagerFactory +Hibernate Listeners + Injection

孤者浪人 提交于 2019-11-29 02:09:54

If you used SessionFactory, this would be the configuration:

<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>

But since you are using JPA, I'm afraid you need to use AOP as outlined in this thread

Or you can

  1. store the ApplicationContext in a ThreadLocal or a custom holder class and expose it through a static method
  2. have a base class for your listeners something like this:

Base class:

public abstract class ListenerBase{

    protected void wireMe(){
        ApplicationContext ctx = ContextHelper.getCurrentApplicationContext();
        ctx.getAutowireCapableBeanFactory().autowireBean(this);
    }

}

Now in your lifycycle methods call wireMe() first.


Update:

Here is a sample implementation of 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(){
    }

}

Wire it in your Spring Bean configuration like this:

<bean class="com.mycompany.ContextHelper" factory-method="getInstance" />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!