Edgaras Karka Edgaras Karka - 1 year ago 137
Java Question

Creating bean error if change Spring data jpa entity package

I use

for get data from mysql.

When my project structure is (Project.java file is in application package) everything works well, but when I put Project.java entity file to entities package I got bellow exception:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'controller': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.gehive.microservice.data.repositories.ProjectRepository com.gehive.microservice.application.Controller.repo; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'projectRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not an managed type: class com.gehive.microservice.data.entities.Project

work without exceptions:

enter image description here

if structure like this I got exception:

enter image description here

Answer Source

The default @ComponntScan for Spring boot(the one that @SpringBootApplication inherits) scans the current package and all it's sub packages.

In the first case Project.java is in the same package as Application.java, so it's ok.

To make Project work from another package change the name to com.gehive.microservice.application.entities or whatever sub-package of the one with the main class.

Usually I keep the bootstraping class and all the configuration classes in package named <com|org|etc>.<myCompany>.<myProject> and then create the other packages as sub packages of this one.

Spring Data JPA has some other conditions related to the packages. Take a look at the Docs