无法在 ApplicationListener 中注入 Hibernate SessionFactory

Can't inject Hibernate SessionFactory in ApplicationListener

我正在构建一个 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。

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException

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

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

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