ICode9

精准搜索请尝试: 精确搜索
首页?>?其他分享> 文章详细

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

2019-09-30 10:21:22??阅读:8??来源: 互联网

标签:spring?spring-boot?spring-mvc


我有一个Spring启动应用程序.

我收到以下错误

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 {
    public BirthDay findByFirstName(String firstName);
}

以下是控制器.

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" })

OR componentScan:

@SpringBootApplication
@ComponentScan("com.company")


标签:spring,spring-boot,spring-mvc

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有