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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34367316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:54:03  来源:igfitidea点击:

Spring Boot @autowired does not work, classes in different package

springspring-mvcspring-boot

提问by Aniket Patil

I have a Spring boot application.

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

I get the following error

我收到以下错误

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

org.springframework.beans.factory.BeanCreationException:创建名为“birthdayController”的 bean 时出错:自动装配依赖项的注入失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:无法自动装配字段:private com.esri.birthdays.dao.BirthdayRepository com.esri.birthdays.controller.BirthdayController.repository; 嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:未找到类型为 [com.esri.birthdays.dao.BirthdayRepository] ​​的合格 bean 依赖项:预计至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注释:{@org.springframework.beans.factory.annotation.Autowired(required=true)} 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor。

Following is code of my Repository class

以下是我的 Repository 类的代码

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

Following is controller.

以下是控制器。

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

    @Autowired
    private BirthdayRepository repository;

Works if they are in same package.Not sure why

如果它们在同一个包中,则有效。不知道为什么

回答by jgr

When you use @SpringBootApplication annotation in for example package

当您在例如包中使用 @SpringBootApplication 注释时

com.company.config

com.company.config

it will automatically make component scan like this:

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

@ComponentScan("com.company.config") 

So it will NOT scan packages like com.company.controller etc.. Thats why you have to declare your @SpringBootApplication in package one level prior to your normal packages like this: com.company OR use scanBasePackages property, like this:

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

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

OR componentScan:

或组件扫描:

@SpringBootApplication
@ComponentScan("com.company")



回答by LucaT

Just put the packages inside the @SpringBootApplication tag.

只需将包放在 @SpringBootApplication 标签中。

@SpringBootApplication(scanBasePackages = { "com.pkg1", "com.pkg2", .....})

Let me know.

让我知道。

回答by mchlfchr

Try annotating your Configuration Class(es) with the @ComponentScan("com.esri.birthdays")annotation. Generally spoken: If you have sub-packages in your project, then you have to scan for your relevant classes on project-root. I guess for your case it'll be "com.esri.birthdays". You won't need the ComponentScan, if you have no sub-packaging in your project.

尝试使用注释来注释您的配置类@ComponentScan("com.esri.birthdays")。一般而言:如果您的项目中有子包,那么您必须在项目根目录中扫描相关类。我猜你的情况是“com.esri.birthdays”。如果您的项目中没有子包,则不需要 ComponentScan。

回答by sasanka

Spring Boot will handle those repositories automatically as long as they are included in the same package (or a sub-package) of your @SpringBootApplication class. For more control over the registration process, you can use the @EnableMongoRepositories annotation. spring.io guides

只要它们包含在 @SpringBootApplication 类的同一个包(或子包)中,Spring Boot 就会自动处理这些存储库。为了更好地控制注册过程,您可以使用 @EnableMongoRepositories 注释。spring.io 指南

@SpringBootApplication
@EnableMongoRepositories(basePackages = {"RepositoryPackage"})
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

回答by Sreeni

For this kind of issue, I ended up in putting @Serviceannotation on the newly created service class then the autowire was picked up. So, try to check those classes which are not getting autowired, if they need the corresponding required annotations(like @Controller, @Service, etc.) applied to them and then try to build the project again.

对于这种问题,我最终在@Service新创建的服务类上添加了注释,然后自动装配。因此,尝试检查未得到自动连接那些类,如果他们需要相应的必须的注解(如@Controller@Service等),适用于他们,然后尝试再次生成项目。

回答by GSB

By default, in Spring boot applications, component scan is done inside the package where your main class resides. any bean which is outside the package will not the created and thus gives the above mentioned exception.

默认情况下,在 Spring 启动应用程序中,组件扫描是在主类所在的包内完成的。包外的任何 bean 都不会被创建,因此给出了上述例外。

Solution: you could either move the beans to the main spring boot class(which is not a good approach) or create a seperate configutation file and import it:

解决方案:您可以将 bean 移动到主 Spring Boot 类(这不是一个好方法)或创建一个单独的配置文件并导入它:

@Import({CustomConfigutation1.class, CustomConfiguration2.class})
@SpringBootpplication
public class BirthdayApplication {

public static void main(String [] args) {
    springApplication.run(BirthdayApplication.class, args );
}

}

}

Add beans to these CustomConfiguration files.

将 bean 添加到这些 CustomConfiguration 文件中。

回答by Nikhil Kakade

In my case @componentwas not working because I initialized that class instance by using new <classname>().

在我的情况下@component不起作用,因为我使用new <classname>().

If we initialize instance by conventional Java way anywhere in code, then spring won't add that component in IOC container.

如果我们在代码中的任何地方通过传统的 Java 方式初始化实例,那么 spring 将不会将该组件添加到 IOC 容器中。

回答by Gemasoft

Try this:

尝试这个:

    @Repository
    @Qualifier("birthdayRepository")
    public interface BirthdayRepository extends MongoRepository<BirthDay,String> {
        public BirthDay findByFirstName(String firstName);
    }

And when injecting the bean:

当注入 bean 时:

    @Autowired
    @Qualifier("birthdayRepository")
    private BirthdayRepository repository;

If not, check your CoponentScanin your config.

如果没有,请在您的配置中检查您的CoponentScan

回答by gurman singh

There will definitely be a bean also containing fields related to Birthday So use this and your issue will be resolved

肯定会有一个 bean 也包含与生日相关的字段 所以使用这个,你的问题将得到解决

@SpringBootApplication
@EntityScan("com.java.model*")  // base package where bean is present
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

回答by Prerit Jain

I had the same problem. It worked for me when i removed the private modifier from the Autowired objects.

我有同样的问题。当我从 Autowired 对象中删除私有修饰符时,它对我有用。