无法在 Spring Boot 中自动装配 @Repository 注释接口

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

Can't Autowire @Repository annotated interface in Spring Boot

springspring-bootspring-datarepositoryspring-data-jpa

提问by visst

I'm developing a spring boot application and I'm running into an issue here. I'm trying to inject a @Repository annotated interface and it doesn't seem to work at all. I'm getting this error

我正在开发一个 Spring Boot 应用程序,但在这里遇到了一个问题。我正在尝试注入一个 @Repository 带注释的接口,但它似乎根本不起作用。我收到这个错误

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springBootRunner': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.pharmacy.persistence.users.dao.UserEntityDao com.pharmacy.config.SpringBootRunner.userEntityDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.pharmacy.persistence.users.dao.UserEntityDao] 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)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
    at com.pharmacy.config.SpringBootRunner.main(SpringBootRunner.java:25)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.pharmacy.persistence.users.dao.UserEntityDao com.pharmacy.config.SpringBootRunner.userEntityDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.pharmacy.persistence.users.dao.UserEntityDao] 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:561)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    ... 16 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.pharmacy.persistence.users.dao.UserEntityDao] 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:1301)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
    ... 18 common frames omitted

Here is my code:

这是我的代码:

Main application class:

主要应用类:

package com.pharmacy.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;


@SpringBootApplication
@ComponentScan("org.pharmacy")
public class SpringBootRunner {


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

Entity class:

实体类:

package com.pharmacy.persistence.users;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;



@Entity
public class UserEntity {

    @Id
    @GeneratedValue
    private Long id;
    @Column
    private String name;

}

Repository interface:

仓库接口:

package com.pharmacy.persistence.users.dao;

import com.pharmacy.persistence.users.UserEntity;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;


@Repository
public interface UserEntityDao extends CrudRepository<UserEntity,Long>{

}

Controller:

控制器:

package com.pharmacy.controllers;

import com.pharmacy.persistence.users.UserEntity;
import com.pharmacy.persistence.users.dao.UserEntityDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class HomeController {


    @Autowired
    UserEntityDao userEntityDao;

    @RequestMapping(value = "/")
    public String hello() {
        userEntityDao.save(new UserEntity("ac"));
        return "Test";

    }
}

build.gradle

构建.gradle

buildscript {
    ext {
        springBootVersion = '1.2.2.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'spring-boot'
mainClassName = "com.pharmacy.config.SpringBootRunner"
jar {
    baseName = 'demo'
    version = '0.0.1-SNAPSHOT'
}


repositories {
    mavenCentral()
}


dependencies {
    compile("org.springframework.boot:spring-boot-starter-data-jpa")
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.springframework.boot:spring-boot-starter-ws")
    compile("postgresql:postgresql:9.0-801.jdbc4")

    testCompile("org.springframework.boot:spring-boot-starter-test")
}

application.properties:

应用程序属性:

spring.view.prefix: /
spring.view.suffix: .html

spring.jpa.database=POSTGRESQL
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=update


spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=abc123

I even compared my code with Accessing data jpa, and I'm running out of ideas what's wrong with this code. Any help appreciated. Thanks in advance.

我什至将我的代码与访问数据 jpa进行了比较,但我想不出这段代码有什么问题。任何帮助表示赞赏。提前致谢。

EDITED: I changed my code as suggested to look like above, and I'm not getting that error when I'm injecting my @Repository interface into another component. However, I have a problem now - my component cannot be retrieved (I used debugging). What I'm doing wrong so spring cannot find my component?

编辑:我按照上面的建议更改了我的代码,当我将@Repository 接口注入另一个组件时,我没有收到该错误。但是,我现在有一个问题 - 无法检索我的组件(我使用了调试)。我做错了什么所以 spring 找不到我的组件?

回答by hang321

When the repository package is different to @SpringBootApplication/@EnableAutoConfiguration, base package of @EnableJpaRepositoriesis required to be defined explicitly.

当存储库包与@SpringBootApplication/ 不同时@EnableAutoConfiguration@EnableJpaRepositories需要明确定义基础包。

Try to add @EnableJpaRepositories("com.pharmacy.persistence.users.dao")to SpringBootRunner

尝试添加@EnableJpaRepositories("com.pharmacy.persistence.users.dao")到 SpringBootRunner

回答by Sanjay Mistry

I had the same issues with Repository not being found. So what I did was to move everything into 1 package. And this worked meaning that there was nothing wrong with my code. I moved the Repos & Entities into another package and added the following to SpringApplication class.

我遇到了与找不到存储库相同的问题。所以我所做的是将所有内容都移动到 1 个包中。这有效意味着我的代码没有任何问题。我将 Repos & Entities 移动到另一个包中,并将以下内容添加到 SpringApplication 类中。

@EnableJpaRepositories("com...jpa")
@EntityScan("com...jpa")

After that, I moved the Service (interface & implementation) to another package and added the following to SpringApplication class.

之后,我将服务(接口和实现)移到另一个包中,并将以下内容添加到 SpringApplication 类中。

@ComponentScan("com...service")

This solved my issues.

这解决了我的问题。

回答by Dherik

There is another cause for this type of problem what I would like to share, because I struggle in this problem for some time and I could't find any answer on SO.

我想分享此类问题的另一个原因,因为我在这个问题上挣扎了一段时间,但在 SO 上找不到任何答案。

In a repository like:

在像这样的存储库中:

@Repository
public interface UserEntityDao extends CrudRepository<UserEntity, Long>{

}

If your entity UserEntitydoes not havethe @Entityannotation on the class, you will have the same error.

如果实体UserEntity不具有@Entity对类注释,你会有同样的错误。

This error is confusing for this case, because you focus on trying to resolve the problem about Spring not found the Repository but the problem is the entity. And if you came to this answer trying to test your Repository, this answermay help you.

对于这种情况,这个错误令人困惑,因为您专注于尝试解决有关 Spring not found the Repository 但问题是实体的问题。如果您来到这个答案试图测试您的存储库,这个答案可能对您有所帮助。

回答by Damien Polegato

It seems your @ComponentScanannotation is not set properly. Try :

看来您的@ComponentScan注释设置不正确。尝试 :

@ComponentScan(basePackages = {"com.pharmacy"})

Actually you do not need the component scan if you have your main class at the top of the structure, for example directly under com.pharmacypackage.

实际上,如果您的主类位于结构的顶部,例如直接在com.pharmacypackage.json下,则不需要组件扫描。

Also, you don't need both

此外,你不需要两者

@SpringBootApplication
@EnableAutoConfiguration

The @SpringBootApplicationannotation includes @EnableAutoConfigurationby default.

@SpringBootApplication注释包括@EnableAutoConfiguration默认。

回答by Vinayak Shenoy

I had a similar issue where I was receiving NoSuchBeanDefinitionExceptionin Spring Boot (basically while working on CRUD repository), I had to put the below annotations on the main class:

NoSuchBeanDefinitionException在 Spring Boot 中遇到了类似的问题(基本上是在处理 CRUD 存储库时),我不得不将以下注释放在主类上:

@SpringBootApplication   
@EnableAutoConfiguration
@ComponentScan(basePackages={"<base package name>"})
@EnableJpaRepositories(basePackages="<repository package name>")
@EnableTransactionManagement
@EntityScan(basePackages="<entity package name>")

Also, make sure you have the @Componentannotations in place on the implementations.

另外,请确保@Component在实现上有注释。

回答by priyank

In SpringBoot, the JpaRepository are not auto-enabled by default. You have to explicitly add

在 SpringBoot 中,默认情况下不会自动启用 JpaRepository。您必须明确添加

@EnableJpaRepositories("packages")
@EntityScan("packages")

回答by rahsan

You are scanning the wrong package:

您正在扫描错误的包裹:

@ComponentScan("**org**.pharmacy")

Where as it should be:

应该在哪里:

@ComponentScan("**com**.pharmacy")

Since your package names start with com and not org.

由于您的包名称以 com 而不是 org.

回答by Bence

Here is the mistake: as someone said before, you are using org.pharmacy insted of com.pharmacy in componentscan

这是错误:正如之前有人所说,您在 componentscan 中使用 org.pharmacy insted of com.pharmacy

    package **com**.pharmacy.config;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.ComponentScan;


    @SpringBootApplication
    @ComponentScan("**org**.pharmacy")
    public class SpringBootRunner {

回答by yogidilip

To extend onto above answers, You can actually add more than one package in your EnableJPARepositories tag, so that you won't run into "Object not mapped" error after only specifying the repository package.

为了扩展上述答案,您实际上可以在 EnableJPARepositories 标签中添加多个包,这样您就不会在仅指定存储库包后遇到“对象未映射”错误。

@SpringBootApplication
@EnableJpaRepositories(basePackages = {"com.test.model", "com.test.repository"})
public class SpringBootApplication{

}

回答by yuen26

In @ComponentScan("org.pharmacy"), you are declaring org.pharmacypackage. But your components in com.pharmacypackage.

在 中@ComponentScan("org.pharmacy"),您正在声明org.pharmacy包。但是你的组件在com.pharmacy包中。