Autowired filed is still null
I have the following class (which is a JPA entity listener):
@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) {
}
}
The filed domainObjectDAO
is recognized by Spring and according to the log, is auto wired.
excerpt from the log:
[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 - Auto开发者_JAVA技巧wiring by type from bean name 'auditLogListener' to bean named 'domainObjectDAO'
But when checking the field in debug mode i see that the fields is null and an exception is thrown when calling the findAll()
method.
Why is the filed null and is there a way to solve this?
Thank you.
JPA listeners are instantiated by JPA provider rather than by Spring, therefore that their dependencies are not injected by Spring. That is, now you have two instances of your class - one used by JPA (without injected dependencies) and another one instantiated by Spring (you see it in the log).
So, you need to inject dependencies into an object that is not managed by Spring. You have two options:
Use
@Configurable
Use some kind of static or thread-bound state to obtain a reference to
ApplicationContext
from your listener. For example, in a typical Spring web application you can obtain it as follows:RequestContextUtils.getWebApplicationContext( (SerlvetRequest) RequestContextHolder.currentRequestAttributes() .resolveReference(RequestAttributes.REFERENCE_REQUEST))
精彩评论