gpt4 book ai didi

java - Spring Boot 出现 UnsatisfiedDependencyException

转载 作者:行者123 更新时间:2023-12-01 18:16:18 28 4
gpt4 key购买 nike

我在 SpringBoot 上遇到困难。我正在学习一门类(class),我的代码与我的教授完全相同,但我的代码给了我这个错误(我尝试使用许多解决方案来修复此问题,例如在另一个 .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 上方或下方的主类中添加了 @EnableJpaRepositories(basePackages = "my.package.*") 并添加了对 pom.xml 的依赖,就像 Jacob 和 Hussain 所说,谢谢大家!

最佳答案

抛出上述异常/错误是因为 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>

关于java - Spring Boot 出现 UnsatisfiedDependencyException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60358129/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com