当前位置: 首页 > 知识库问答 >
问题:

UnsatisfiedDependencyException与springboot

赫连子石
2023-03-14

我在springboot遇到困难。我正在学习一个课程类,我的代码和我的教授完全一样,但我的代码给了我这个错误(我已经尝试了很多解决方案来解决这个问题,比如在另一个.xml中创建一个bean,在main类中使用@EntityScan和@ComponentScan,但没有任何东西对我有用):

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.4.RELEASE)

2020-02-22 21:15:17.728  INFO 8108 --- [           main] br.com.luis.restwithspringboot.Main      : Starting Main on DESKTOP-HVESQU8 with PID 8108 (started by lucar in C:\Users\lucar\IdeaProjects\RestWithSpringBootUdemy\02 RestWithSpringBootInitialzr)
2020-02-22 21:15:17.731  INFO 8108 --- [           main] br.com.luis.restwithspringboot.Main      : No active profile set, falling back to default profiles: default
2020-02-22 21:15:18.842  INFO 8108 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-02-22 21:15:18.850  INFO 8108 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-02-22 21:15:18.851  INFO 8108 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.30]
2020-02-22 21:15:18.951  INFO 8108 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-02-22 21:15:18.952  INFO 8108 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1178 ms
2020-02-22 21:15:18.992  WARN 8108 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'personController': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'personService': Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'br.com.luis.restwithspringboot.repository.PersonRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2020-02-22 21:15:18.994  INFO 8108 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2020-02-22 21:15:19.083  INFO 8108 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-02-22 21:15:19.174 ERROR 8108 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field repository in br.com.luis.restwithspringboot.services.PersonService required a bean of type 'br.com.luis.restwithspringboot.repository.PersonRepository' that could not be found.

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


Action:

Consider defining a bean of type 'br.com.luis.restwithspringboot.repository.PersonRepository' in your configuration.


Process finished with exit code 1

我的主要类:

package br.com.luis.restwithspringboot;

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

@SpringBootApplication
@ComponentScan({ "br.com.luis.restwithspringboot.*" })
public class Main {

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

}

我的PersonRepository类:

package br.com.luis.restwithspringboot.repository;

import br.com.luis.restwithspringboot.model.Person;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface PersonRepository extends JpaRepository<Person, Long> {

}

我的PersonService类:

package br.com.luis.restwithspringboot.services;

import br.com.luis.restwithspringboot.exceptions.ResourceNotFoundException;
import br.com.luis.restwithspringboot.model.Person;
import br.com.luis.restwithspringboot.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PersonService {

    @Autowired
    PersonRepository repository;

    public Person create(Person person) {
        return repository.save(person);
    }

    public List<Person> findAll() {
        return repository.findAll();
    }

    public Person findById(Long id) {

        return repository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("No records found for this ID"));
    }

    public Person update(Person person) {
        Person entity = repository.findById(person.getId())
                .orElseThrow(() -> new ResourceNotFoundException("No records found for this ID"));

        entity.setFirstName(person.getFirstName());
        entity.setLastName(person.getLastName());
        entity.setAddress(person.getAddress());
        entity.setGender(person.getGender());

        return repository.save(entity);
    }

    public void delete(Long id) {
        Person entity = repository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("No records found for this ID"));
        repository.delete(entity);
    }

}

我的PersonController类:

package br.com.luis.restwithspringboot.controllers;

import br.com.luis.restwithspringboot.model.Person;
import br.com.luis.restwithspringboot.services.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/person")
public class PersonController {

    @Autowired
    private PersonService service;

    @GetMapping
    public List<Person> findAll() {
        return service.findAll();
    }

    @GetMapping("/{id}")
    public Person findById(@PathVariable("id") Long id) {
        return service.findById(id);
    }

    @PostMapping
    public Person create(@RequestBody Person person) {
        return service.create(person);
    }

    @PutMapping
    public Person update(@RequestBody Person person) {
        return service.update(person);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> delete(@PathVariable("id") Long id) {
        service.delete(id);
        return ResponseEntity.ok().build();
    }
}

我的pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>br.com.luis</groupId>
    <artifactId>restwithspringboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>restwithspringboot</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>11</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

所有pom.xml都是由Intellij思想的spring Initializr生成的。我希望任何人都能帮助我。谢谢伙计们!如果你需要任何其他代码,请告诉我,我会立即发送。

编辑:

使用@enableJParepositories(basePackages=“br.luis.RestWithSpringBoot.*”):

      .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.4.RELEASE)

2020-02-22 21:58:00.228  INFO 6888 --- [           main] br.com.luis.restwithspringboot.Main      : Starting Main on DESKTOP-HVESQU8 with PID 6888 (started by lucar in C:\Users\lucar\IdeaProjects\RestWithSpringBootUdemy\02 RestWithSpringBootInitialzr)
2020-02-22 21:58:00.232  INFO 6888 --- [           main] br.com.luis.restwithspringboot.Main      : No active profile set, falling back to default profiles: default
2020-02-22 21:58:00.791 ERROR 6888 --- [           main] o.s.boot.SpringApplication               : Application run failed

java.lang.NoClassDefFoundError: org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessor
    at org.springframework.data.jpa.repository.config.JpaRepositoryConfigExtension.<clinit>(JpaRepositoryConfigExtension.java:76) ~[spring-data-jpa-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.data.jpa.repository.config.JpaRepositoriesRegistrar.getExtension(JpaRepositoriesRegistrar.java:46) ~[spring-data-jpa-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupport.registerBeanDefinitions(RepositoryBeanDefinitionRegistrarSupport.java:101) ~[spring-data-commons-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.lambda$loadBeanDefinitionsFromRegistrars$1(ConfigurationClassBeanDefinitionReader.java:385) ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:684) ~[na:na]
    at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsFromRegistrars(ConfigurationClassBeanDefinitionReader.java:384) ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:148) ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:120) ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:331) ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:236) ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:275) ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:95) ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:706) ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:532) ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) ~[spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) ~[spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) ~[spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at br.com.luis.restwithspringboot.Main.main(Main.java:14) ~[classes/:na]
Caused by: java.lang.ClassNotFoundException: org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581) ~[na:na]
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178) ~[na:na]
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) ~[na:na]
    ... 21 common frames omitted

解决了:在主类中添加了@enableJPararePositories(basePackages=“My.Package.*”),在@SpringBootApplication之上或之下添加了对pom.xml的依赖,就像Jacob和Hussain所说的,谢谢伙计们!

共有1个答案

羊舌富
2023-03-14

抛出上述异常/错误是因为Java类加载器找不到在工件“spring-orm”下可用的类“PersistenceanNotationBeanPostProcessor”。

应通过添加以下依赖项来解决问题

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

添加上述依赖项后,可能会出现“无法配置数据源”的情况,因为项目中没有定义数据库配置。您可以通过添加以下依赖项来使用嵌入式数据库。H2以下的依赖项会出现内存中的数据库。

<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
</dependency>
 类似资料:
  • 原因:org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为“DBUtils”的bean时出错:通过字段“bn repo”表示的未满足的依赖项;嵌套异常为org.springframework.beans.factory.noSuchBeanDefinitionException:没有“.*.DataAccess.

  • Microsoft Windows[版本10.0.18362.1016](c)2019 Microsoft Corporation。保留所有权利。

  • 将@service添加到控制器后,单元测试失败。该项目是Spring-boot V2.0.1版本。我花了很多时间想找到答案,但没有成功。在我添加@service注释之前,测试工作正常,并且我的服务类在其中有一个存储库。 堆栈跟踪: 2018-04-24 12:57:12.487警告940--[main]O.s.w.cs.GenericWebApplicationContext:上下文初始化过程中遇

  • 我面临着我自己无法解决的问题。我想当有Spring经验的人检查时,解决方案可能是显而易见的。 我有一个非常简单的存储库: 就我而言,对象应该在中创建,然后注入到测试类的中。由于某种原因,它根本没有发生。我将感谢任何可能导致解决这个问题的帮助或暗示。

  • 我是构建web服务的新手,我开始使用spring boot构建web服务。我创建了以下controller类 尝试运行我的web服务会导致它抛出以下异常: 但是,如果我移除“ScheduledThreadPoolExecutor”和构造函数,它运行良好。谁能解释一下扩展课程有什么问题吗? 注: 1)扩展类是在下面提到的文章中建议的,作为我最初问题的解决方案。最初,我的runnable在没有任何类型

  • 问题内容: 几天来,我一直在尝试创建Spring CRUD应用程序。我糊涂了。我无法解决此错误。 还有这个 客户端控制器 ClientServiceImpl 客户资料库 我浏览了许多类似的问题,但是没有人回答不能帮助我。 问题答案: ClientRepository应该用标记注释。使用你当前的配置,Spring将不会扫描该类并对其有所了解。在启动和连接时,找不到ClientRepository类。