Java 使用@Configurable在JPA实体侦听器中注入Springbean
我尝试使用Java 使用@Configurable在JPA实体侦听器中注入Springbean,java,spring,jpa,aspectj,configurable,Java,Spring,Jpa,Aspectj,Configurable,我尝试使用@Configurable在@PostPersist侦听器中注入Springbean @Configurable @EnableSpringConfigured public class BankAccountAuditListener { @PersistenceContext private EntityManager em; @PostPersist public void createAudit(BankAccount bankAccount){ ... } }
@Configurable
在@PostPersist
侦听器中注入Springbean
@Configurable
@EnableSpringConfigured
public class BankAccountAuditListener {
@PersistenceContext
private EntityManager em;
@PostPersist
public void createAudit(BankAccount bankAccount){
...
}
}
侦听器由@EntityListeners({BankAccountAuditListener.class})调用
我将其放在spring配置xml文件中:
<context:annotation-config/>
<context:spring-configured/>
<context:load-time-weaver/>
在createAudit(…)
函数中,em
始终为空
我缺少什么?好的,BankAccountAuditListener是在spring的ApplicationContext准备好使用之前由Hibernate创建的。可能这就是我无法在其中注入任何内容的原因。您可以在JPAEventListener类中使用延迟初始化的bean,该bean在第一次持久化实体时初始化
然后在延迟加载的bean上使用@Configurable。
这可能不是最好的解决方案,但可以快速解决
public class JPAEntityListener{
/**
* Hibernate JPA EntityListEner is not spring managed and gets created via reflection by hibernate library while entitymanager is loaded.
* Inorder to inject business rules via Spring use lazy loaded bean which makes use of @Configurable
*/
private CustomEntityListener listener;
public JPAEntityListener() {
super();
}
@PrePersist
public void onEntityPrePersist(TransactionalEntity entity) {
if (listener == null) {
listener = new CustomEntityListener();
}
listener.onEntityPrePersist(entity);
}
@PreUpdate
public void onEntityPreUpdate(TransactionalEntity entity) {
if (listener == null) {
listener = new CustomEntityListener();
}
listener.onEntityPreUpdate(entity);
}}
以及您的惰性加载bean类
@Configurable(autowire = Autowire.BY_TYPE)
public class CustomEntityListener{
@Autowired
private Environment environment;
public void onEntityPrePersist(TransactionalEntity entity) {
//custom logic
}
你把javaagent换成spring/aspectj了吗?@marchewa,我记得,是的。但经过几次迭代后,我放弃了AspectJ方法。