Spring JPAHibernate EmptyInterceptor不注入EntitymanagerSpring Bean

Spring JPAHibernate EmptyInterceptor不注入EntitymanagerSpring Bean,第1张

Spring JPA / Hibernate EmptyInterceptor不注入Entitymanager / Spring Bean

AuditEmptyInterceptor
不是由Spring管理的豆,它是由Hibernate来实例化,所以你不能依赖注入它。

您可以改用静态委托:

public class StaticDelegateInterceptor extends EmptyInterceptor {    private static Interceptor interceptor;    public static void setInterceptor(Interceptor interceptor) {        StaticDelegate.interceptor = interceptor;    }    public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {      return StaticDelegate.interceptor.onSave(entity, id, state, propertyNames, types);    }    ...}

在页面上注册StaticDelegateInterceptor

persistence.xml

<persistence>    <persistence-unit name="xxx" transaction-type="RESOURCE_LOCAL">       <class>com.xxx</class>       ...       ...       <properties>          <property name="hibernate.ejb.interceptor"        value="com.company.demo.audit.StaticDelegateInterceptor" />       </properties>   </persistence-unit></persistence>

修改您当前的AuditEmptyInterceptor,使其在StaticDelegateInterceptor中进行注册:

@Named@Transactionalpublic class AuditEmptyInterceptor extends EmptyInterceptor {     @PostConstruct     public void init() {          StaticDelagateInterceptor.setInterceptor(this);     }     ...}

最后

entityManagerFactory
auditEmptyInterceptor
通过设置depends-on属性来确保您的bean依赖于您:

<bean id="entityManagerFactory"p:dataSource-ref="dataSource" p:jpaVendorAdapter-ref="jpaAdapter"depends-on="auditEmptyInterceptor" >...</bean>


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5501553.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存