我有几个 Spring boot 项目。出于这个问题的目的,假设我有以下包含这些类的项目:
MyProject-commons:
cz.myproject.commons.model.MyEntity;
我的项目工作人员:
cz.myproject.worker.repository.EntityRepository;
MyProject-worker
将 MyProject-commons
作为 Maven 依赖项。
EntityRepository
是 MyEntity
的 Spring JPA 存储库:
public interface ImageMetadataRepository extends CrudRepository<MyEntity, Long> {
}
问题是我在这个设置中总是遇到以下异常:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'EntityRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not an managed type: class cz.myproject.commons.model.MyEntity
如果我将存储库移动到以下包 (cz.myproject.repository.EntityRepository
),一切都会开始工作!我很困惑为什么包结构会影响这样的行为。
有人可以解释一下发生了什么以及如何让它与我描述的包结构一起工作吗?感谢您的任何提示!
我的 Spring boot application.java:
@SpringBootApplication
@EnableJpaRepositories(basePackages = "cz.myproject.worker.repository")
@EntityScan(basePackages = "cz.myproject.commons.model")
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
最佳答案
Spring Boot
将扫描 @Entity
类(如果它们位于您指定 @SpringBootApplication
注解的同一包或子包中) .
您必须使用@EntityScan注释,因为您的实体
位于不同的包中。
@EntityScan(basePackages = "cz.myproject.commons.model")
或
@EntityScan(basePackageClasses=MyEntity.class)
.
我们可以使用 basePackageClasses
,而不是指定 basePackages
属性,这样 package
其中 MyEntity.java
> 存在将被扫描。
来自 Spring Boot documentation -
public @interface EntityScan
Configures the LocalContainerEntityManagerFactoryBean to scan for entity classes in the classpath. This annotation provides an alternative to manually setting LocalContainerEntityManagerFactoryBean.setPackagesToScan(String...) and is particularly useful if you want to configure entity scanning in a type-safe way, or if your LocalContainerEntityManagerFactoryBean is auto-configured. A LocalContainerEntityManagerFactoryBean must be configured within your Spring ApplicationContext in order to use entity scanning. Furthermore, any existing packagesToScan setting will be replaced.
One of basePackageClasses(), basePackages() or its alias value() may be specified to define specific packages to scan. If specific packages are not defined scanning will occur from the package of the class with this annotation.
关于java - 包结构影响托管类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35334309/