gpt4 book ai didi

java - 包结构影响托管类

转载 作者:行者123 更新时间:2023-12-01 10:26:30 25 4
gpt4 key购买 nike

我有几个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com