我有以下类(它是JPA实体侦听器):
@Service
public class AuditLogListener {
@Autowired
IDomainObjectDAO domainObjectDAO;
@PostLoad
public void saveOldData(DomainObject obj) {
domainObjectDAO.findAll();
System.out.println("after Load");
}
@PreUpdate
public void logChanges(DomainObject obj) {
}
}
Run Code Online (Sandbox Code Playgroud)
domainObjectDAOSpring会识别该字段,并根据日志自动进行连线。
摘录自日志:
[http-8080-1] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Found injected element on class [com.legolas.entityListeners.AuditLogListener]: AutowiredFieldElement for com.legolas.dao.interfaces.IDomainObjectDAO com.legolas.entityListeners.AuditLogListener.domainObjectDAO
[http-8080-1] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Eagerly caching bean 'auditLogListener' to allow for resolving potential circular references
[http-8080-1] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'auditLogListener': AutowiredFieldElement for com.legolas.dao.interfaces.IDomainObjectDAO com.legolas.entityListeners.AuditLogListener.domainObjectDAO
[http-8080-1] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'domainObjectDAO'
[http-8080-1] DEBUG org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - Autowiring by type from bean name 'auditLogListener' to bean named 'domainObjectDAO'
Run Code Online (Sandbox Code Playgroud)
但是,当在调试模式下检查该字段时,我看到该字段为null,并且在调用该findAll()方法时抛出异常。
为什么字段为null,有没有办法解决这个问题?
谢谢。
JPA侦听器是由JPA提供程序而不是Spring实例化的,因此,它们的依赖项不会由Spring注入。也就是说,现在您有该类的两个实例-一个由JPA使用(没有注入的依赖项),另一个由Spring实例化(在日志中看到它)。
因此,您需要将依赖项注入到不受Spring管理的对象中。您有两种选择:
使用某种静态或线程绑定状态ApplicationContext从您的侦听器获取引用。例如,在典型的Spring Web应用程序中,您可以按以下方式获取它:
RequestContextUtils.getWebApplicationContext(
(SerlvetRequest) RequestContextHolder.currentRequestAttributes()
.resolveReference(RequestAttributes.REFERENCE_REQUEST))
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
4319 次 |
| 最近记录: |