【问题标题】:UnsatisfiedDependencyException with springboot春季启动时出现 UnsatisfiedDependencyException
【发布时间】:2020-06-07 00:47:46
【问题描述】:

我在 SpringBoot 上遇到了困难。我正在上一门课程,我的代码与我的教授完全一样,但我的代码给了我这个错误(我试图用许多解决方案来解决这个问题,比如在另一个 .xml 中创建一个 bean,在主类中用 @ 注释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 IDEA 的 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

已解决:在 @SpringBootApplication 上方或下方的 Main 类中添加了 @EnableJpaRepositories(basePackages = "my.package.*") 并像 Jacob 和 Hussain 所说的那样添加了对 pom.xml 的依赖,谢谢大家!

【问题讨论】:

  • 你好像不见了@EnableJpaRepositories
  • @JacobG。 @EnableJpaRepositores(basePackages = "my package here") 对吗?我编辑了我的帖子,但有例外
  • 您还需要在您的pom.xml 中依赖spring-boot-starter-data-jpa
  • 非常感谢,我已经找了 4 个小时了,只是最后一个问题,我的 GET 请求给了我和异常“无效的列名”,但我已经改变了将列名改为正确的名称并不断出现此异常

标签: java spring


【解决方案1】:

由于 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>

【讨论】:

  • 谢谢,实际上我使用的是 SQL Server,但它给了我“无效的列名”,但在每个地方我只是复制粘贴名称,它在数据库上的写法,任何想法错误?
  • 你能分享一下你的模型课吗?
  • 我的 application.properties 看起来像下面 spring.datasource.url=jdbc:mysql://localhost:3306/testdb?useSSL=false spring.datasource.username=root spring.datasource.password= spring .jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
  • 对于 hibernate5,我通过将下一行放入 application.properties 文件 spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl spring.jpa 解决了这个问题.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl 否则默认将 firstName 映射到 first_name。
猜你喜欢
  • 1970-01-01
  • 2015-10-05
  • 2014-03-14
  • 2017-09-11
  • 2015-04-18
  • 2017-06-24
  • 2015-08-22
  • 2015-09-18
  • 2015-03-20
相关资源
最近更新 更多