不能在 Spring 引导中使用 Autowire@Repository 注释接口

我正在开发一个弹簧启动应用程序,这里遇到了一个问题。我试图注入一个@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$1.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

这是我的代码:

主要申请类别:

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

实体类别:

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;


}

存储库接口:

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";


}
}

建造,分级

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

应用性能:

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

我甚至将我的代码与 访问数据 jpa进行了比较,我已经不知道这段代码出了什么问题。 Any help appreciated. Thanks in advance.

编辑: 我按照上面的建议修改了我的代码,当我将@Repository 接口注入到另一个组件中时,我没有得到这个错误。但是,我现在有一个问题-我的组件无法检索(我使用了调试)。我做错了什么让春天找不到我的组成部分?

243914 次浏览

似乎您的 @ComponentScan注释设置不正确。 试试:

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

实际上,如果将主类放在结构的顶部,例如直接放在 com.pharmacy包下,则不需要进行组件扫描。

而且,你不需要两者兼顾

@SpringBootApplication
@EnableAutoConfiguration

默认情况下,@SpringBootApplication注释包括 @EnableAutoConfiguration

当存储库包与 @SpringBootApplication/@EnableAutoConfiguration不同时,需要显式定义 @EnableJpaRepositories的基本包。

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

I had a similar problem but with a different cause:

在我的例子中,问题是在定义存储库的接口中

public interface ItemRepository extends Repository {..}

I was omitting the types of the template. Setting them right:

public interface ItemRepository extends Repository<Item,Long> {..}

成功了。

我也有同样的问题,仓库没有被找到。所以我所做的就是把所有东西都放到一个包里。这样就意味着我的代码没有任何问题。我将 Repos & Entities 移动到另一个包中,并将以下内容添加到 SpringApplication 类中。

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

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

@ComponentScan("com...service")

这解决了我的问题。

我在 Spring Boot 中接收 NoSuchBeanDefinitionException时遇到过类似的问题(基本上是在处理 CRUD 存储库时) ,我必须在主类上放置以下注释:

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

另外,确保在实现中已经有了 @Component注释。

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

在储存库中,比如:

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


}

如果您的实体 UserEntity 没有类上的 @Entity注释,您将会有相同的错误。

这个错误对于本例来说是令人困惑的,因为您关注于解决 Spring 没有找到 Repository 但问题是实体的问题。如果你得到了这个答案,试图测试你的仓库,这个答案可能会帮助你。

这个话题我也有一些问题。 您必须确保在 Spring 引导运行程序类中定义包,如下面的示例所示:

@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan({"controller", "service"})
@EntityScan("entity")
@EnableJpaRepositories("repository")
public class Application {


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

希望这个能帮上忙!

你扫描错了软件包:

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

应该在的地方:

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

因为您的包名以 com 而不是 org 开头。

这里有一个错误: 正如有人之前所说的,在组件扫描中,您使用的是 org.drug 而不是 com.drug

    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 {

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

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


}

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

如果您在使用 @DataJpaTest进行单元测试时遇到了这个问题,那么您将在下面找到解决方案。

Spring boot do not initialize @Repository beans for @DataJpaTest. So try one of the two fix below to have them available:

首先

使用 @SpringBootTest代替。但是这将启动整个应用程序上下文。

第二 (更好的解决方案)

导入所需的特定存储库,如下所示

@DataJpaTest
@Import(MyRepository.class)
public class MyRepositoryTest {


@Autowired
private MyRepository myRepository;

在 SpringBoot 中,JpaRepository 默认情况下不会自动启用

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

可能和你的包装有关,我也有过类似的问题:

Description:
Field userRepo in com.App.AppApplication required a bean of type 'repository.UserRepository' that could not be found.


The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)

行动:

考虑在配置中定义一个类型为“ repository.UserRepository”的 bean。 "

Solved it by put the repository files into a package with standardised naming convention:

e.g. com.app.Todo (for main domain files)

还有

com.app.Todo.repository (for repository files)

这样,Spring 就知道去哪里寻找存储库,否则事情很快就会变得混乱。 :)

希望这个能帮上忙。

SpringDataMongoDB 也有类似的问题: 我必须将包路径添加到 @EnableMongoRepositories

确保尝试自动连接存储库的 @Service@Component不在与 SpringApplication.class相同的目录中。确保它在像 service/这样的子文件夹中。

@SpringBootApplication(scanBasePackages=,<youur package name>)
@EnableJpaRepositories(<you jpa repo package>)
@EntityScan(<your entity package>)


Entity class like below
@Entity
@Table(name="USER")
public class User {


@Id
@GeneratedValue

有时候,当我忘记在 maven 配置中添加龙目岛注释处理器依赖项时,我也会遇到同样的问题

I resolved that issue by changing that dependency :

<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>

就这个:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

这样就没有必要使用如下的注释:

@EnableAutoConfiguration
@ComponentScan({"controller", "service"})
@EntityScan("entity")
@EnableJpaRepositories("repository")

)

添加以下对 pom.xml 的依赖性解决了这个问题

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

如果您的主类在 com.example 包中,那么您的其他类应该在不同的包中,应该在 com.example 包中调用; 即: 控制器软件包 控制器

还有

Main 类应该位于 com.example 中,而不是 com.example.Main 中 如果您将主类包设置为 com.example.main,那么另一个应该位于该包中,例如 com.package.main.controller

上面的许多答案很有帮助,因为它们是整个解决方案的一部分。对我来说,这是他们中的一些人的混合。

您的 ComponentScan软件包错误。请将其更改为:

@ComponentScan("com.pharmacy")

你还必须补充:

@EnableJpaRepositories

to your SpringBootApplication class, here: SpringBootRunner.

我必须改变 Maven 的依赖关系(类似于 Gradle 的工作方式) :

<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>

致:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

不要忘记刷新您的依赖关系。

然后,我还必须将 Entity类中的导入更改为:

import jakarta.persistence.*;