Java Can';t在ApplicationListener中注入Hibernate SessionFactory
我正在构建一个SpringBoot应用程序,并试图通过编程方式填充我的测试数据库 我想到了这个:Java Can';t在ApplicationListener中注入Hibernate SessionFactory,java,spring,hibernate,blob,Java,Spring,Hibernate,Blob,我正在构建一个SpringBoot应用程序,并试图通过编程方式填充我的测试数据库 我想到了这个: @Profile("dev") @Component public class DatabaseFillerOnStartup implements ApplicationListener<ContextRefreshedEvent> { @Resource private SomeRepository someRepository; @Resource //This doesn't
@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) {
...
问题是我无法注入sessionFactory
原因:org.springframework.beans.factory.NoSuchBean定义异常
是否有更好的方法来实现我的目标?您没有显示会话工厂的配置位置。您是在@Configuration注释类中使用SessionFactory还是通过标准的xmlbean配置连接SessionFactory 编辑:
基于这个答案,请检查。我使用的是spring boot starter数据jpa。这真的是我第一个白手起家的项目,所以有些东西只是自己工作,我还不知道是怎么回事。多亏了riversidetraveler的回答,我设法找到了另一个同样有用的线索。
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);
}
}