gpt4 book ai didi

Spring Boot @autowired 不起作用,不同包中的类

转载 作者:IT老高 更新时间:2023-10-28 13:48:55 33 4
gpt4 key购买 nike

我有一个 Spring Boot 应用程序。

我收到以下错误

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'birthdayController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.esri.birthdays.dao.BirthdayRepository com.esri.birthdays.controller.BirthdayController.repository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.esri.birthdays.dao.BirthdayRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE] at or

以下是我的 Repository 类的代码

package com.esri.birthdays.dao;
import com.esri.birthdays.model.BirthDay;
public interface BirthdayRepository extends MongoRepository<BirthDay,String> {
public BirthDay findByFirstName(String firstName);
}

下面是 Controller 。

package com.esri.birthdays.controller;
@RestController
public class BirthdayController {

@Autowired
private BirthdayRepository repository;

如果它们在同一个包中就可以工作。不知道为什么

最佳答案

当你在例如包中使用@SpringBootApplication注解时

com.company.config

它会像这样自动进行组件扫描:

@ComponentScan("com.company.config") 

所以它不会扫描 com.company.controller 等包。这就是为什么你必须在你的普通包之前的一级声明你的 @SpringBootApplication 包,如下所示:com.company 或使用 scanBasePackages 属性,如下所示:

@SpringBootApplication(scanBasePackages = { "com.company" })

或组件扫描:

@SpringBootApplication
@ComponentScan("com.company")


关于Spring Boot @autowired 不起作用,不同包中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34367316/

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