【问题标题】:Can't inject Hibernate SessionFactory in ApplicationListener无法在 ApplicationListener 中注入 Hibernate SessionFactory
【发布时间】:2016-05-19 23:35:31
【问题描述】:

我正在构建一个 SpringBoot 应用程序,并尝试以编程方式填充我的测试数据库。

我想出了这个:

@Profile("dev")
@Component
public class DatabaseFillerOnStartup implements ApplicationListener<ContextRefreshedEvent> {

@Resource
private SomeRepository someRepository;

@Resource //This doesn't work
private SessionFactory sessionFactory;

@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
    ...

我的一个实体有一个 Blob,我想在其中保存图像:

   private Blob createBlobWithSampleImage() {
    InputStream imageStream = this.getClass().getClassLoader().getResourceAsStream("sample1.jpg");
    LobCreator lobCreator = Hibernate.getLobCreator(sessionFactory.getCurrentSession());
    try {
        return lobCreator.createBlob(IOUtils.toByteArray(imageStream));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

问题是我无法注入 sessionFactory。

原因:org.springframework.beans.factory.NoSuchBeanDefinitionException

有没有更好的方法来实现我想要的?

【问题讨论】:

标签: java spring hibernate blob


【解决方案1】:

您没有显示您在哪里配置了会话工厂。您是使用spring-boot-starter-data-jpa 还是您自己在@Configuration 注释类中或通过标准xml bean 配置连接SessionFactory?

编辑: 根据该答案查看this stackoverflow answer

【讨论】:

  • 我正在使用 spring-boot-starter-data-jpa。这真的是我从头开始的第一个项目,所以有些事情只是自己工作,我还不知道如何。
猜你喜欢
  • 2017-05-04
  • 2015-05-11
  • 2018-03-22
  • 2015-05-19
  • 2017-04-10
  • 2019-03-21
  • 2020-04-21
  • 1970-01-01
  • 2017-10-23
相关资源
最近更新 更多