Cannot resolve reference to bean ‘entityManagerFactory’ while setting constructor argument

spring transactional annotation

If you have encountered this problem while you are configuring Spring Data JPA repositories in your application, you are not alone. Don’t be afraid, there is a simple solution for that.

Let me provide you a piece of code that could cause this problem:

Note that this is a partial configuration code, not the whole source code.

Here pay attention to the name of the Bean method: entityManagerF

In a Spring @Bean method, the name of the bean registered in the application context will be equal to the name of the method itself unless otherwise specified. Here we are registering an EntityManagerFactory bean named “entityManagerF”. But the JPA API is, by convention, looking for an EntityManagerFactory bean named “entityManagerFactory”. In order to fix this problem there are 2 things you can do.

1- Change the name of the method as entityManagerFactory like so:

 

2- Specify the name of the EntityManagerFactory bean that is used by @EnableJpaRepositories annotation to create repositories discovered through this annotation. “entityManagerFactoryRef” attribute can be used for this job. entityManagerFactoryRef configures the name of the EntityManagerFactory bean definition to be used to create repositories discovered through this annotation.

More info: @EnableJpaRepositories

 

Hope this helps.
Good Luck,
Serdar