【问题标题】:Spring MVC, injection of Hibernate Service into Spring bean is failing, not sure whySpring MVC,将 Hibernate Service 注入 Spring bean 失败,不知道为什么
【发布时间】:2011-06-09 21:42:16
【问题描述】:

我有一个在 applicationContext 中配置的 spring bean,如下所示:

<bean id="beanIRPlus" class="org.jadefalcon.demo.server.Spring.beans.BeanIRPlus" />

然后我有一个如下所示的 Hibernate 服务,我正在尝试将其注入 Spring bean。通常,例如,如果我使用注入到我的控制器中的原型 bean 并且具有注入的 Hibernate 服务,它可以正常工作,但是对于这个特定的 bean,它是一个单例,因此它是在应用程序启动时创建的。我什至确保将 bean 声明放在 applicationContext.xml 文件的最后,认为它可能必须放在与 Hibernate 相关的任何内容之后,但问题仍然存在。它给出了一个空指针异常,即CasesService 对象不存在。非常感谢任何关于我做错了什么的建议:

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.jadefalcon.demo.domain.Cases;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("casesservice")
@Transactional
public class CasesService {

    protected static Logger logger = Logger.getLogger("service");

    @Resource(name = "sessionFactory")
    private SessionFactory sessionFactory;

    public void add(Cases cases) {
        logger.debug("Saving new search");

        // Retrieve session from Hibernate
        Session session = sessionFactory.getCurrentSession();

        // Save
        session.save(cases);
    }
}

【问题讨论】:

  • 请同时发布配置文件(applicationContext.xml)

标签: java hibernate spring dependency-injection autowired


【解决方案1】:

我没有看到你是如何尝试注入它的。您至少有两种选择:

  • xml。在控制器 bean 定义中定义 &lt;property name=".." ref="casesservice"&gt;
  • 注释。使用@Autowired private CaseService service(或@Inject)

【讨论】:

  • 抱歉没有包括在内,我正在使用@Autowired,它只是一种普通的注入方式,我以前用过很多次,我试图注入(Hibernate 服务对象)为null 基于我上面描述的一组情况(它是在应用程序启动时实例化的单例 bean)
  • 如果你使用@Autowired,你的上下文xml中有&lt;context:component-scan&gt;吗?如果没有配置,这很难诊断 - 只需发布即可。
  • 既然您使用的是@Autowired,那么您的BeanIRPlus 类是否有@Component(或@Service)?
猜你喜欢
  • 2014-10-06
  • 2017-08-24
  • 2017-08-29
  • 2015-08-19
  • 2014-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-14
相关资源
最近更新 更多