java - 包结构影响托管类

标签 java spring-boot package

我有几个 Spring boot 项目。出于这个问题的目的,假设我有以下包含这些类的项目:

MyProject-commons: cz.myproject.commons.model.MyEntity;

我的项目工作人员: cz.myproject.worker.repository.EntityRepository;

MyProject-workerMyProject-commons 作为 Maven 依赖项。

EntityRepositoryMyEntity 的 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/

相关文章:

java - JScrollPane 无法与 FormLayout 一起使用

java - Java/Android 中现有对象的短期引用的开销

java - 无法执行语句

spring - Spring Boot 2.0.1升级后的疯狂HTTP问题

java - 在不可变请求类中使用 Lombok

path - 将包安装到自定义目录 Composer

python - 将模块转换为包时出错

java - Gradle javax.jms 依赖项未下载

spring-boot - spring-boot-actuator 是否会改变 spring 应用程序的上下文根?

android - 以编程方式获取 PNG 或 BMP 格式的 Android 包图标