java 自动装配依赖项的注入失败,无法自动装配字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36811274/
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-11-03 01:53:17  来源:igfitidea点击:

Injection of autowired dependencies failed, Could not autowire field

javaspringautowired

提问by Dennie

I know this question has been asked a lot and I am risking a double (or triple or quadruple) topic, but the proposed solutions don't seem to work for me.

我知道这个问题被问了很多,我冒着双重(或三重或四重)主题的风险,但提议的解决方案似乎对我不起作用。

I'm having trouble with the much dreaded cannot autowire error. First time setting up a complete Spring project from scratch, so I don't really know what the problem is.

我遇到了可怕的无法自动装配错误的麻烦。第一次从头搭建一个完整的Spring项目,所以我真的不知道是什么问题。

This is my current setup: ProjectRepo:

这是我当前的设置:ProjectRepo:

package be.italent.repo;

import be.italent.model.Project;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ProjectRepo extends JpaRepository<Project, Integer> {

}

ProjectService:

项目服务:

package be.italent.services;

import be.italent.model.Project;
import be.italent.repo.ProjectRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProjectService {

    @Autowired
    private ProjectRepo projectRepo;

    public List<Project> getAllProjects() {
        return projectRepo.findAll();
    }
}

ProjectRestController:

项目休息控制器:

package be.italent.controllers;

import java.util.ArrayList;
import be.italent.services.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import be.italent.model.Project;

@RestController
@RequestMapping("/projects")
public class ProjectRestController {

    @Autowired
    private ProjectService projectService;

    @RequestMapping(method = RequestMethod.GET, produces="application/json")
    public ArrayList<Project> getProjects(){
        ArrayList<Project> c = (ArrayList<Project>) projectService.getAllProjects();

        return c;
    }
}

spring-mvc.xml

spring-mvc.xml

...
<context:component-scan base-package="be.italent"></context:component-scan>
...

Error:

错误:

SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'projectRestController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private be.italent.services.ProjectService be.italent.controllers.ProjectRestController.projectService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'projectService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private be.italent.repo.ProjectRepo be.italent.services.ProjectService.projectRepo; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [be.italent.repo.ProjectRepo] 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.preInstantiateSingletons(DefaultListableBeanFactory.java:700) 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:5068) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5584) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1572) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1562) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private be.italent.services.ProjectService be.italent.controllers.ProjectRestController.projectService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'projectService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private be.italent.repo.ProjectRepo be.italent.services.ProjectService.projectRepo; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [be.italent.repo.ProjectRepo] 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) ... 22 more Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'projectService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private be.italent.repo.ProjectRepo be.italent.services.ProjectService.projectRepo; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [be.italent.repo.ProjectRepo] 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:1014) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:957) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:855) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480) ... 24 more Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private be.italent.repo.ProjectRepo be.italent.services.ProjectService.projectRepo; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [be.italent.repo.ProjectRepo] 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) ... 35 more Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [be.italent.repo.ProjectRepo] 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:1100) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:855) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480) ... 37 more

严重:异常将上下文初始化事件发送到类 org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException:创建名为“projectRestController”的 bean 时出错:自动装配依赖项的注入失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:无法自动装配字段:private be.italent.services.ProjectService be.italent.controllers.ProjectRestController.projectService; 嵌套异常是 org.springframework.beans.factory.BeanCreationException:创建名为“projectService”的 bean 时出错:自动装配依赖项的注入失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:无法自动装配字段:private be.italent.repo.ProjectRepo be.italent.services。ProjectService.projectRepo; 嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:未找到类型为 [be.italent.repo.ProjectRepo] 的合格 bean 依赖项:预期至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注释:{@org.springframework.beans.factory.annotation.Autowired(required=true)} 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292) 在 org.springframework.beans factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) 在 org. ContainerBase$StartChild.call(ContainerBase.java:1572) 在 org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1562) 在 java.util.concurrent.FutureTask.run(FutureTask.java:266)在 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) 在 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) 在 java.lang.Thread.run(Thread.java:745) ) 引起:org.springframework.beans.factory.BeanCreationException: 无法自动装配字段:private be.italent.services.ProjectService be.italent.controllers.ProjectRestController.projectService; 嵌套异常是 org.springframework.beans.factory.BeanCreationException:创建名为“projectService”的 bean 时出错:自动装配依赖项的注入失败;嵌套异常是 org. springframework.beans.factory.BeanCreationException:无法自动装配字段:private be.italent.repo.ProjectRepo be.italent.services.ProjectService.projectRepo; 嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:未找到类型为 [be.italent.repo.ProjectRepo] 的合格 bean 依赖项:预期至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注释:{@org.springframework.beans.factory.annotation.Autowired(required=true)} 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508) 在 org.springframework. beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) 在 org.springframework.beans.factory.annotation。AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289) ... 22 more 嵌套异常是 org.springframework.beans.factory.BeanCreationException:无法自动装配字段:private be.italent.repo.ProjectRepo be.italent.services.ProjectService.projectRepo; 嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:未找到类型为 [be.italent.repo.ProjectRepo] 的合格 bean 依赖项:预期至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注释:{@org.springframework.beans.factory.annotation.Autowired(required=true)} 在 org. 24 更多 引起:org.springframework.beans.factory.BeanCreationException:无法自动装配字段:private be.italent.repo.ProjectRepo be.italent.services.ProjectService.projectRepo; 嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有找到类型为 [be.italent.repo.ProjectRepo] 的合格 bean 依赖项:预计至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注释:{@org.springframework.beans.factory.annotation.Autowired(required=true)} 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508) 在 org.springframework. beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) 在 org.springframework.beans。factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289) ... 35个原因:org.springframework.beans.factory.NoSuchBeanDefinitionException:没有找到符合依赖关系的[be.italent.repo.ProjectRepo]类型的bean:预计至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注释:{@org.springframework.beans.factory.annotation.Autowired(required=true)} 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1100) 在 org.springframework.beans。 factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960) 在 org.springframework.beans.factory.support。

Any help? Thanks!

有什么帮助吗?谢谢!

Solution

解决方案

Added this to my spring-mvc.xml:

将此添加到我的 spring-mvc.xml 中:

<beans
...
jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

...

<jpa:repositories base-package="be.italent.repo" entity-manager-factory-ref="emf"/>

回答by Jesper

When something is wrong when initializing the application context, Spring often gives these long stack traces. Usually you can find out what the ultimate cause is by looking at the bottom of the stack trace.

当初始化应用程序上下文时出现问题时,Spring 通常会给出这些长堆栈跟踪。通常,您可以通过查看堆栈跟踪的底部来找出最终原因。

In your case you see this error message at the bottom:

在您的情况下,您会在底部看到此错误消息:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [be.italent.repo.ProjectRepo] found

org.springframework.beans.factory.NoSuchBeanDefinitionException:找不到类型为 [be.italent.repo.ProjectRepo] 的合格 bean

This means that Spring cannot find a bean of type ProjectRepo.

这意味着 Spring 找不到类型为 的 bean ProjectRepo

Your ProjectReporepository interface is in package be.italent.repo, which is a subpackage of be.italent, which is component-scanned, so the problem is not that it is in a wrong package.

您的ProjectRepo存储库接口在 package 中be.italent.repo,它是 的子包be.italent,它是组件扫描的,所以问题不在于它在错误的包中。

Did you forget to enable Spring Data JPA?

您是否忘记启用 Spring Data JPA?

When you use XML configuration (as you are doing now), you have to have a repositoriesXML tag in your config file:

当您使用 XML 配置时(就像您现在所做的那样),您repositories的配置文件中必须有一个XML 标记:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/data/jpa
           http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

    <!-- Tell Spring Data JPA where your repository interfaces are -->
    <jpa:repositories base-package="be.italent.repo" />

    <!-- ... -->
</beans>

When you use JavaConfig, you can do it with an annotation:

当您使用 JavaConfig 时,您可以使用注释来实现:

@Configuration
@EnableJpaRepositories("be.italent.repo")
public class MySpringConfiguration {
    // ...
}

回答by Sineth Lakshitha

Problem is in the ProjectRestController.java You have used @Autowired for ProjectService 1)

问题出在 ProjectRestController.java 您已将 @Autowired 用于 ProjectService 1)

  1. Remove @Autowired annotation.
  2. Genarate getters and setter from projectService.
  3. Set a Bean for ProjectServicein spring.xml
  1. 删除@Autowired 注释。
  2. 生成 getter 和 setter 从projectService.
  3. ProjectService在 spring.xml 中设置一个 Bean

now run your application. It works for me.

现在运行您的应用程序。这个对我有用。