我创建了一个库,用于在多个 Spring Boot 应用程序上共享代码。
该库包含一个 Repository 类 RequestRepository
。将库添加到 Spring Boot 项目后,编译并成功运行单元测试。
// Library: RequestRepository.java
package org.test.lib;
public interface RequestRepository extends CrudRepository<Request, Integer> {}
// Application: Application.java
package org.test.app;
@SpringBootApplication
@ComponentScan(basePackages = {"org.test.app", "org.test.lib"})
public class Application {
// ...
}
当 Spring 尝试 Autowiring 存储库时,启动应用程序会引发 NoSuchBeanDefinitionException
。
Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException
: No qualifying bean of type 'org.test.lib.repositories.RequestRepository
' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
我为组件扫描启用了 DEBUG 日志记录,并获得了有关存储库的以下输出。
2018-07-10 08:33:25.035 DEBUG 14976 --- [ main] .i.s.PathMatchingResourcePatternResolver : Resolved location pattern [classpath*:org/test/lib/**/*.class] to resources [URL [jar:file:/C:/Users/.../lib-request-1.0.0-SNAPSHOT.jar!/org/test/lib/repositories/RequestRepository.class], ...
我错过了什么吗?
最佳答案
您必须使用 @EnableJpaRepositories
显式启用 Spring Boot 应用程序外部的存储库。
@SpringBootApplication
@EnableJpaRepositories(basePackages = {"org.test.app", "org.test.lib"})
@ComponentScan(basePackages = {"org.test.app", "org.test.lib"})
public class Application {
// ...
}
参见Spring guide .
By default, Spring Boot will enable JPA repository support and look in the package (and its subpackages) where
@SpringBootApplication
is located. If your configuration has JPA repository interface definitions located in a package not visible, you can point out alternate packages using@EnableJpaRepositories
and its type-safebasePackageClasses=MyRepository.class
parameter.
用于使用库集@EntityScan
中的@Entity
类。
关于java - 库中存储库的 NoSuchBeanDefinitionException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51258828/