【问题标题】:Autowired filed is still null自动装配字段仍然为空
【发布时间】:2011-05-09 21:01:36
【问题描述】:

我有以下类(它是一个 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) {

    }

}

domainObjectDAO 被 Spring 识别并根据日志自动连接。

日志摘录:

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

但是在调试模式下检查字段时,我看到字段为空,并且在调用findAll() 方法时抛出异常。

为什么归档为空,有没有办法解决这个问题?

谢谢。

【问题讨论】:

标签: java spring jpa


【解决方案1】:

JPA 侦听器由 JPA 提供程序而不是 Spring 实例化,因此它们的依赖项不是由 Spring 注入的。也就是说,现在您有两个类的实例 - 一个由 JPA 使用(没有注入依赖项),另一个由 Spring 实例化(您可以在日志中看到它)。

因此,您需要将依赖项注入到不受 Spring 管理的对象中。你有两个选择:

  • 使用@Configurable

  • 使用某种静态或线程绑定状态从您的侦听器获取对ApplicationContext 的引用。例如,在一个典型的 Spring Web 应用程序中,您可以通过以下方式获取它:

    RequestContextUtils.getWebApplicationContext(
        (SerlvetRequest) RequestContextHolder.currentRequestAttributes()
            .resolveReference(RequestAttributes.REFERENCE_REQUEST))
    

【讨论】:

  • 我使用了@Configurable Annotation,在日志中我现在在日志中看到 bean 被注入到 JPA 实体管理器中,这意味着由 JPA 提供程序实例化的 Bean 可以识别该字段(我是对的?),但该字段仍然为空。
  • @Noam:您是否按照@Configurable 的要求配置了加载时间编织?
  • 不知道那是什么,我会检查并回复您。
  • 加载时间编织不适合我的需要,我选择了第二个选项,它工作正常。谢谢
猜你喜欢
  • 2015-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-01
相关资源
最近更新 更多