You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SessionFactory注入失败始终为null,求排查解决方法

问题根源:初始化时机踩坑啦!

你在MyService类里直接把session和tx声明为类级别变量,还立刻调用sessionFactory.openSession()——这时候Spring根本还没完成sessionFactory的注入啊!Spring创建Bean的流程是先实例化对象,再注入依赖,你这相当于在对象刚创建、依赖还没到位的时候就硬要用它,可不就返回null嘛。

修复方案:把会话/事务逻辑移到方法内部

直接把session和事务的初始化逻辑挪到persistData()方法里,这样每次调用方法时,sessionFactory已经被Spring妥妥注入好了:

@Component 
public class MyService { 
    @Autowired 
    private SessionFactory sessionFactory; 

    public void persistData(){ 
        // 把会话和事务的创建移到方法内部,确保依赖已注入
        Session session = sessionFactory.openSession(); 
        Transaction tx = session.beginTransaction(); 
        try {
            // 你的数据持久化逻辑写在这里
            ...
            tx.commit(); 
        } catch (Exception e) {
            // 异常时记得回滚事务,避免数据不一致
            if (tx != null) {
                tx.rollback();
            }
            throw e; // 抛出异常让上层处理
        } finally {
            // 确保会话关闭,防止资源泄漏
            if (session != null) {
                session.close();
            }
        }
    } 
}
额外优化:用Spring声明式事务更省心

其实没必要手动管理session和事务,Spring的声明式事务能帮你一键搞定,代码更简洁还不容易出错:

@Component 
@Transactional // 加上这个注解,Spring自动管事务
public class MyService { 
    @Autowired 
    private SessionFactory sessionFactory; 

    public void persistData(){ 
        Session session = sessionFactory.getCurrentSession(); 
        // 直接写持久化逻辑就行,不用手动开事务、关会话
        ...
    } 
}

另外还要确认:你的主类上有@SpringBootApplication(Spring Boot项目),并且MyService和CommandLineApp在主类的同包或子包下(或者用@ComponentScan指定扫描路径),保证Spring能扫描到这些组件。

内容的提问来源于stack exchange,提问作者Roland

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:46:59