未找到依赖项:预计至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注解:

Posted

技术标签:

【中文标题】未找到依赖项:预计至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注解:【英文标题】:No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: 【发布时间】:2014-11-23 14:36:41 【问题描述】:

我正在尝试使用 Spring 编写一个 SOAP 服务,但是我收到了一个依赖注入问题。我通过这样的服务使用@Autowired 时遇到问题:

    public interface UserDao 
    User getUser(String username);

Dao 的实现如下:

  @Controller("userDao")
    public class UserDaoImpl implements UserDao 
    private static Log log = LogFactory.getLog(UserDaoImpl.class);

    @Autowired
    @Qualifier("sessionFactory")
    private LocalSessionFactoryBean sessionFactory;

    @Override
    public User getUser(String username) 
        Session session = sessionFactory.getObject().openSession();
        // Criteria query = session.createCriteria(Student.class);
        Query query = session
                .createQuery("from User where username = :username");
        query.setParameter("username", username);
        try 
            System.out.println("\n Load Student by ID query is running...");
            /*
             * query.add(Restrictions.like("id", "%" + id + "%",
             * MatchMode.ANYWHERE)); return (Student) query.list();
             */
            return (User) query.uniqueResult();
         catch (Exception e) 
            // TODO: handle exception
            log.info(e.toString());
         finally 
            session.close();
        
        return null;
    


public interface UserBo 
    User loadUser(String username);

public class UserBoImpl implements UserBo 
    @Autowired
    private UserDao userDao;

    @Override
    public User loadUser(String username) 
        // TODO Auto-generated method stub
        return userDao.getUser(username);
    




@WebService
@Component
public class UserService 

    @Autowired
    private UserBo userBo;

    @WebMethod(operationName = "say")
    public String sayHello(String name) 
        return ("Hello Java to " + name);
    

    @WebMethod(operationName = "getUser")
    public User getUser(String username) 
        return userBo.loadUser(username);
    

下面是xml映射文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ws="http://jax-ws.dev.java.net/spring/core"
    xmlns:wss="http://jax-ws.dev.java.net/spring/servlet"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://jax-ws.dev.java.net/spring/core
    http://jax-ws.java.net/spring/core.xsd
    http://jax-ws.dev.java.net/spring/servlet
    http://jax-ws.java.net/spring/servlet.xsd

    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    <context:annotation-config />

    <context:component-scan base-package="edu.java.spring.ws"></context:component-scan>
    <context:component-scan base-package="edu.java.spring.ws.dao"></context:component-scan>
    <bean id="userDao" class="edu.java.spring.ws.dao.UserDaoImpl"></bean>
    <!-- <context:component-scan base-package="edu.java.spring.ws.bo"></context:component-scan>
     -->
    <wss:binding url="/user">
        <wss:service>
            <ws:service bean="#userService" />
        </wss:service>
    </wss:binding>
    <bean id="userBo" class="edu.java.spring.ws.bo.impl.UserBoImpl"></bean>
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/contentdb" />
        <property name="username" value="root" />
        <property name="password" value="123456" />
    </bean>
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
        <property name="packagesToScan" value="edu.java.spring.ws.model" />
    </bean>
</beans>

而部署时抛出的错误是: 这是更新的堆栈跟踪:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.sun.xml.ws.transport.http.servlet.SpringBinding#0' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot create inner bean '(inner bean)#538071ba' of type [org.jvnet.jax_ws_commons.spring.SpringService] while setting bean property 'service'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#538071ba' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean 'userService' while setting bean property 'bean'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.java.spring.ws.bo.UserBo edu.java.spring.ws.UserService.userBo; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userBo': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.java.spring.ws.dao.UserDao edu.java.spring.ws.bo.impl.UserBoImpl.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [edu.java.spring.ws.dao.UserDao] 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.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:290)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:129)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1456)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1197)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4992)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5490)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#538071ba' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean 'userService' while setting bean property 'bean'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.java.spring.ws.bo.UserBo edu.java.spring.ws.UserService.userBo; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userBo': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.java.spring.ws.dao.UserDao edu.java.spring.ws.bo.impl.UserBoImpl.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [edu.java.spring.ws.dao.UserDao] 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.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:336)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1456)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1197)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:276)
    ... 24 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.java.spring.ws.bo.UserBo edu.java.spring.ws.UserService.userBo; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userBo': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.java.spring.ws.dao.UserDao edu.java.spring.ws.bo.impl.UserBoImpl.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [edu.java.spring.ws.dao.UserDao] 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:292)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
    ... 30 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.java.spring.ws.bo.UserBo edu.java.spring.ws.UserService.userBo; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userBo': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.java.spring.ws.dao.UserDao edu.java.spring.ws.bo.impl.UserBoImpl.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [edu.java.spring.ws.dao.UserDao] 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$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
    ... 38 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userBo': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.java.spring.ws.dao.UserDao edu.java.spring.ws.bo.impl.UserBoImpl.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [edu.java.spring.ws.dao.UserDao] 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:292)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1017)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
    ... 40 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.java.spring.ws.dao.UserDao edu.java.spring.ws.bo.impl.UserBoImpl.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [edu.java.spring.ws.dao.UserDao] 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$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
    ... 51 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [edu.java.spring.ws.dao.UserDao] 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.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1103)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:963)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
    ... 53 more

【问题讨论】:

你能添加你的UserDao类的实现吗?是注释为Reporitory吗? 抱歉,我错过了为 Dao 附加实现。我更新如上。 请按照@Jens 的要求添加存储库注释。还要在映射文件中创建一个条目。 +nILESH:我添加了实现方法。请再次检查。 抱歉捎带这个谷歌结果说:如果你在重构一些东西后无法找出问题所在,请检查以确保你没有移动过调用服务的方法......进入同一个服务。然后,如果你已经够累了,也许你犯了一个错误,试图将服务自动连接到自身中。 【参考方案1】:

查看异常:

No qualifying bean of type [edu.java.spring.ws.dao.UserDao] found for dependency

这意味着没有可用的 bean 来满足这种依赖关系。是的,你有一个接口的实现,但是你还没有为那个实现创建一个 bean。你有两个选择:

@Component@Repository 注释UserDaoImpl,让组件扫描为您完成工作,就像您使用UserService 所做的一样。 手动将 bean 添加到您的 xml 文件中,与您对 UserBoImpl 所做的相同。

请记住,如果您显式创建 bean,则需要将定义放在组件扫描之前。在这种情况下,顺序很重要。

【讨论】:

我真的在 xml 文件中创建了一个 bean。请再次检查以帮助我。谢谢 如果您在 xml 文件中显式添加 bean 的定义,那么它必须放在创建依赖 bean 的组件扫描之前。我会改进答案。【参考方案2】:

UserDaoImpl的实现中添加注解@Repository

@Repository
public class UserDaoImpl implements UserDao 
    private static Log log = LogFactory.getLog(UserDaoImpl.class);

    @Autowired
    @Qualifier("sessionFactory")
    private LocalSessionFactoryBean sessionFactory;

    //...


【讨论】:

我按照你的建议试过了,但效果不好。跟踪日志如下 创建名为 'userDaoImpl' 的 bean 时出错:注入自动装配的依赖项失败;嵌套异常 isorg.springframework.beans.factory.BeanCreationException:无法自动装配字段:私有 org.springframework.orm.hibernate4.LocalSessionFactoryBean edu.java.spring.ws.dao.impl.UserDaoImpl.sessionFactory;嵌套异常是 org.springframework.beans.factory.CannotLoadBeanClassException:找不到名为“userDao”的 bean 的类 [edu.java.spring.ws.dao.UserDaoImpl] @user2659694 看看here 也许这有帮助。【参考方案3】:

在我的例子中,应用程序上下文没有加载,因为我添加了@DataJpaTest 注释。当我将其更改为 @SpringBootTest 时,它可以工作。

@DataJpaTest 仅加载 Spring Boot 应用程序的 JPA 部分。在 JavaDoc 中:

可以与@RunWith(SpringRunner.class) 结合使用的注释,用于典型的 JPA 测试。可以在测试关注 JPA 组件时使用。 使用此注解将禁用完全自动配置,而是仅应用与 JPA 测试相关的配置。

默认情况下,使用@DataJpaTest 注释的测试将使用嵌入式内存数据库(替换任何显式或通常自动配置的数据源)。 @AutoConfigureTestDatabase 注释可用于覆盖这些设置。 如果您希望加载完整的应用程序配置,但使用嵌入式数据库,则应考虑将 @SpringBootTest@AutoConfigureTestDatabase 结合使用,而不是此注释。

【讨论】:

【参考方案4】:

我在 impl 类之前添加了@Service 并且错误消失了。

@Service
public class FCSPAnalysisImpl implements FCSPAnalysis

【讨论】:

【参考方案5】:

您似乎缺少 UserDao 接口的实现。如果您仔细查看异常,它会显示

找不到 [edu.java.spring.ws.dao.UserDao] 类型的合格 bean 依赖:

@Autowired 的工作方式是它会自动查找您通过接口注入的依赖项的实现。在这种情况下,由于没有 UserDao 接口的有效实现,您会收到错误。请确保您有此类的有效实现,并且您的错误应该消失。

希望对您有所帮助。

【讨论】:

【参考方案6】:

我刚刚解决了我的测试中发生的这个错误。

只需确保您的测试类在被测试类的属性中具有所有依赖项,并使用@MockBean 进行注释,这样 SpringBoot 测试上下文就可以正确连接您的类。

如果您正在测试控制器:您还需要类注释来正确加载控制器上下文。

检查一下:

@DisplayName("UserController Adapter Test")
@WebMvcTest(UserController.class)
@AutoConfigureMockMvc(addFilters = false)
@Import(TestConfig.class)
public class UserControllerTest 

@Autowired
private MockMvc mockMvc;

@Autowired
private ObjectMapper objectMapper;

@MockBean
private CreateUserCommand createUserCommand;

@MockBean
private GetUserListQuery getUserListQuery;

@MockBean
private GetUserQuery getUserQuery;

【讨论】:

花了 7 个小时才发现你的答案!谢谢。【参考方案7】:

我们面临这个问题,但有不同的原因,原因如下:

在我们的项目中发现多个具有相同 bean 名称的 bean 条目。 applicationcontext.xml 中有 1 个,dispatcherServlet.xml 中有 1 个

示例:

<bean name="dataService" class="com.app.DataServiceImpl">
<bean name="dataService" class="com.app.DataServiceController">

& 我们正在尝试按 dataService 名称自动装配。

解决方案: 我们更改了 bean 名称并解决了它。

【讨论】:

【参考方案8】:

就我而言,我必须将@Service 注释从接口移动到实现类。

【讨论】:

请解释一下。 在我的类中添加@Service 解决了这个问题,我的类现在被spring注入框架自动拾取。但是,我不明白 为什么 :( p.s. 添加 atComponent 也可以!这是一个较低级别的类,所以我会改用它。【参考方案9】:

在您的 DAO 实现类之前添加存储库注释。 示例:

@Repository
public class EmpDAOImpl extends BaseNamedParameterJdbcDaoSupportUAM 
implements EmpDAO 

【讨论】:

【参考方案10】:

我能有多种原因吗?但是您可能会忘记为您已完成 @Autowired 的组件添加为 @Bean。

在我的情况下,我忘了用 @Bean 进行装饰,这导致了这个问题。

【讨论】:

【参考方案11】:

就我而言,我的项目结构如下:

当我运行测试时,我不断收到关于 facadekafka 属性的 auro-wiring 问题 - 错误返回了有关丢失实例的信息,即使test 和 API 类位于同一个包中。显然那些没有被扫描。

真正有帮助的是添加 @Import 注释将缺失的类带到 Spring 类路径并使其被实例化。

【讨论】:

【参考方案12】:

当您使用@DataJpaTest 时,您需要使用@Import 显式加载类。它不会自动加载你。

【讨论】:

【参考方案13】:

对我来说,罪魁祸首是依赖的大小。

一些项目相关的依赖没有正确下载,导致了这个错误。与具有类似设置的队友检查并再次添加罐子。

【讨论】:

【参考方案14】:

就我而言,我通过在测试类中使用@MockBean 注释器从控制器类导入所有自动装配的依赖项(使用@Autowired 注释)来解决它。例如:

Controller.java

@Autowired
private Service service

@Autowired
private Dao daoService

ControllerTest.java

@MockBean
private Service service

@MockBean
private Dao daoService

请记住,仅当您的测试侧重于类而不是整个应用时,才需要这样做。避免此错误的另一种方法是使用@SprintTest 而不是@WebMvcTest(Controller.class) 一次加载整个应用程序。这个guide 有更多关于测试基础知识的信息,可能会有所帮助。

【讨论】:

【参考方案15】:

我错过了添加

@Controller("userBo") into UserBoImpl class.

解决方案是将此控制器添加到 Impl 类中。

【讨论】:

我不同意这个答案!请重新访问并查看您添加的所有内容。 请等我再检查。 你的 BO 不是控制器! 不要仅仅因为它是您的答案而将其标记为“已接受”。找到最佳答案并接受它。

以上是关于未找到依赖项:预计至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注解:的主要内容,如果未能解决你的问题,请参考以下文章

预计至少有 1 个 bean 有资格作为 autowire 候选者

为啥我不能将此 Spring Boot 服务类注入 JUnit 测试类?预计至少有 1 个 bean 有资格作为 autowire 候选者

没有为依赖找到类型 [org.hibernate.SessionFactory] ​​的匹配 bean

Spring,Bean,constructor-arg as String

引诱框架:预计至少有 1 个参数,得到 0

判断一个数组是不是至少有一个重复项的最快算法