Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument
spring 5.+jpa 配置類出錯:
十二月 20, 2018 5:53:01 下午 org.springframework.web.servlet.DispatcherServlet initServletBean
嚴重: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'studentRepository': Cannot create inner bean '(inner bean)#69ecc373' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#69ecc373': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
原因之一是配置類中方法名不對:
@Bean public LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean() { //EntityManagerFactory LocalContainerEntityManagerFactoryBean bean=new LocalContainerEntityManagerFactoryBean(); bean.setDataSource(dataSource()); bean.setPackagesToScan(new String[] {"com.jpa.demo"}); bean.setJpaVendorAdapter(jpaVendorAdapter()); return bean; }
必須是:entityManagerFactory:
@Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { //EntityManagerFactory LocalContainerEntityManagerFactoryBean bean=new LocalContainerEntityManagerFactoryBean(); bean.setDataSource(dataSource()); bean.setPackagesToScan(new String[] {"com.jpa.demo"}); bean.setJpaVendorAdapter(jpaVendorAdapter()); return bean; }