当我启动应用程序时,我遇到异常,Spring抱怨UnsatisfiedDependencyException:
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'applicationConfig': Unsatisfied dependency expressed through field 'controlRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean found for dependency [com.oak.api.finance.repository.ControlRepository]: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:569)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
我的申请按以下格式组织:
我使用正确的Spring JPA注释声明了我的存储库接口:
@RepositoryRestResource(collectionResourceRel = "exchange", path = "exchanges")
public interface ControlRepository extends PagingAndSortingRepository<Control, Long> {
}
我注释了包含EntryPoint
方法的main
类
@SpringBootApplication
@EntityScan(basePackages = {"com.oak.api.finance.model.dto"})
@EnableJpaRepositories(basePackages = {"com.oak.api.finance.repository"})
public class EntryPoint {
public static void main(String[] args) {
Logger logger = LogManager.getLogger(EntryPoint.class);
logger.info("Starting application");
ApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationConfig.class);
// SpringApplication.run(EntryPoint.class, args);
ctx.getBean(ApplicationServer.class).start();
}
我使用@Autowired
将我的存储库注入我的spring配置(基于java)ApplicationConfig
类:
@Autowired
private ControlRepository controlRepository;
@Autowired
private CompanyRepository companyRepository;
@Autowired
private SectorRepository sectorRepository;
基本上我想控制对Spring的依赖并将其限制为几个包(存储库,java配置和程序入口点 - EntryPoint)
我认为,通过使用我的存储库所在的包指定@EnableJpaRepositories,spring将为我的存储库创建一个代理并实例化该实例,并且当我调用时:
ApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationConfig.class)
存储库实例将存在于bean poole中,并且可以将它们自动装入我的ApplicationConfig
上下文中,然后将它们注入我的控制器。
这显然没有发生,Spring正在抱怨缺少Bean来自动装配,但我不确定我错过了什么。
答案 0 :(得分:1)
我的猜测是你的存储库没有被扫描,因此结果bean没有被创建。你能尝试删除这两个注释
吗?@EntityScan(basePackages = {"com.oak.api.finance.model.dto"})
@EnableJpaRepositories(basePackages = {"com.oak.api.finance.repository"})
仅保留@SpringBootApplication
。如果这不起作用,您可能需要检查包结构(如果可能,请在此处粘贴屏幕截图)
用
替换@SpringBootApplication
@Configuration
@EnableAutoConfiguration
@ComponentScan("com.oak")
使用
new SpringApplicationBuilder()
.sources(SpringBootApp.class)
.web(false)
.run(args);
或者将ComponentScan路径更改为“com.oak”后使用CommandLineRunner,如mh-dev建议