Field Repository in Controller required a bean of type Repository that could not be found

huangapple go评论68阅读模式
英文:

Field Repository in Controller required a bean of type Repository that could not be found

问题

Here is the translated content you requested:

我在这里首次发帖。
我正在学习Spring Boot,并一直试图让我的Spring Boot应用程序运行一段时间了。
我认为我的存储库可能有问题,因为当我将以下行添加到我的控制器类时:

@Autowired
private StoreCardRepository storeCardRepository;

我收到以下错误消息:

2023-05-09T23:39:44.036-07:00 INFO 433094 --- [ main] example.storecard.StoreCardApplication : 使用Java 18.0.2.1启动StoreCardApplication,PID为433094(/media/ryuga/656464b7-2c1e-4da4-8da9-54f5442a88fe/ryuga/IdeaProjects/storecard/target/classes在/media/ryuga/656464b7-2c1e-4da4-8da9-54f5442a88fe/ryuga/IdeaProjects/storecard中启动)
2023-05-09T23:39:44.037-07:00 INFO 433094 --- [ main] example.storecard.StoreCardApplication : 未设置活动配置文件,退回到1个默认配置文件:"default"
2023-05-09T23:39:44.371-07:00 INFO 433094 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : 使用端口(s)初始化Tomcat:8080(http)
2023-05-09T23:39:44.376-07:00 INFO 433094 --- [ main] o.apache.catalina.core.StandardService : 启动服务[Tomcat]
2023-05-09T23:39:44.376-07:00 INFO 433094 --- [ main] o.apache.catalina.core.StandardEngine : 启动Servlet引擎:[Apache Tomcat/10.1.8]
2023-05-09T23:39:44.411-07:00 INFO 433094 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : 初始化Spring嵌入式WebApplicationContext
2023-05-09T23:39:44.412-07:00 INFO 433094 --- [ main] w.s.c.ServletWebServerApplicationContext : 根WebApplicationContext:初始化完成,耗时356毫秒
2023-05-09T23:39:44.435-07:00 WARN 433094 --- [ main] ConfigServletWebServerApplicationContext : 上下文初始化期间遇到异常-取消刷新尝试:org.springframework.beans.factory.UnsatisfiedDependencyException:通过字段'storeCardRepository'表示的未满足的依赖关系创建bean的错误:没有类型为'example.storecard.StoreCardRepository'的合格bean可用:预期至少有1个合格的bean作为自动装配候选者。依赖注释:{@org.springframework.beans.factory.annotation.Autowired(required=true)}
2023-05-09T23:39:44.436-07:00 INFO 433094 --- [ main] o.apache.catalina.core.StandardService : 停止服务[Tomcat]
2023-05-09T23:39:44.443-07:00 INFO 433094 --- [ main] .s.b.a.l.ConditionEvaluationReportLogger : 

启动应用程序时出错。要显示条件评估报告,请以'debug'模式重新运行应用程序。
2023-05-09T23:39:44.450-07:00 ERROR 433094 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter : 

***************************
应用程序启动失败
***************************

描述:

在example.storecard.StoreCardController的字段storeCardRepository中需要类型为'example.storecard.StoreCardRepository'的bean,但找不到。

注入点具有以下注释:
- @org.springframework.beans.factory.annotation.Autowired(required=true)

操作:

考虑在您的配置中定义一个类型为'example.storecard.StoreCardRepository'的bean。

进程以退出代码1结束

这是您的项目结构:

显示文件位置

以下是example.storecard文件中每个文件的代码:

StoreCard.java

package example.storecard;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public record StoreCard(@Id Long id, Double amount) {
}

StoreCardApplication.java

package example.storecard;

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

@SpringBootApplication
public class StoreCardApplication {

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

}

StoreCardController.java

package example.storecard;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

@RestController
@RequestMapping("/storecards")
public class StoreCardController {

    @Autowired
    private StoreCardRepository storeCardRepository;

    @GetMapping("/{requestedId}")
    public ResponseEntity<StoreCard> findById(@PathVariable Long requestedId){
        Optional<StoreCard> storeCard = storeCardRepository.findById(requestedId);
        if(storeCard.isPresent()){
            return ResponseEntity.ok(storeCard.get());
        }
        return ResponseEntity.notFound().build();
    }

}

StoreCardRepository.java

package example.storecard;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface StoreCardRepository extends CrudRepository<StoreCard, Long> {
}

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>3.0.6</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>example</groupId>
	<artifactId>storecard</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>StoreCard</name>
	<description>StoreCard service for woodland water store</description>
	<properties>
		<java.version>17</java.version>
	</properties>
	<dependencies>
		<dependency>


<details>
<summary>英文:</summary>

First post here.
I am learning spring boot and I&#39;ve been stuck with trying to get my spring boot application to run for a while.
I assume something with my repository is wrong since when I add the line to my controller class

@Autowired
private StoreCardRepository storeCardRepository;


I get the following error:

2023-05-09T23:39:44.036-07:00 INFO 433094 --- [ main] example.storecard.StoreCardApplication : Starting StoreCardApplication using Java 18.0.2.1 with PID 433094 (/media/ryuga/656464b7-2c1e-4da4-8da9-54f5442a88fe/ryuga/IdeaProjects/storecard/target/classes started by ryuga in /media/ryuga/656464b7-2c1e-4da4-8da9-54f5442a88fe/ryuga/IdeaProjects/storecard)
2023-05-09T23:39:44.037-07:00 INFO 433094 --- [ main] example.storecard.StoreCardApplication : No active profile set, falling back to 1 default profile: "default"
2023-05-09T23:39:44.371-07:00 INFO 433094 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2023-05-09T23:39:44.376-07:00 INFO 433094 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2023-05-09T23:39:44.376-07:00 INFO 433094 --- [ main] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/10.1.8]
2023-05-09T23:39:44.411-07:00 INFO 433094 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2023-05-09T23:39:44.412-07:00 INFO 433094 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 356 ms
2023-05-09T23:39:44.435-07:00 WARN 433094 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'storeCardController': Unsatisfied dependency expressed through field 'storeCardRepository': No qualifying bean of type 'example.storecard.StoreCardRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2023-05-09T23:39:44.436-07:00 INFO 433094 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2023-05-09T23:39:44.443-07:00 INFO 433094 --- [ main] .s.b.a.l.ConditionEvaluationReportLogger :

Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2023-05-09T23:39:44.450-07:00 ERROR 433094 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :


APPLICATION FAILED TO START


Description:

Field storeCardRepository in example.storecard.StoreCardController required a bean of type 'example.storecard.StoreCardRepository' 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 'example.storecard.StoreCardRepository' in your configuration.

Process finished with exit code 1


Here is my project structure
[Showing where files are at](https://i.stack.imgur.com/s45Oi.png)

And here is the code for each of the files in example.storecard:


StoreCard.java

package example.storecard;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public record StoreCard(@Id Long id, Double amount) {
}


StoreCardApplication.java

package example.storecard;

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

@SpringBootApplication
public class StoreCardApplication {

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

}


StoreCardController.java

package example.storecard;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

@RestController
@RequestMapping("/storecards")
public class StoreCardController {

@Autowired
private StoreCardRepository storeCardRepository;


@GetMapping(&quot;/{requestedId}&quot;)
public ResponseEntity&lt;StoreCard&gt; findById(@PathVariable Long requestedId){
    Optional&lt;StoreCard&gt; storeCard = storeCardRepository.findById(requestedId);
    if(storeCard.isPresent()){
        return ResponseEntity.ok(storeCard.get());
    }
    return ResponseEntity.notFound().build();


}

}


StoreCardRepository.java

package example.storecard;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface StoreCardRepository extends CrudRepository<StoreCard, Long> {
}


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&quot;>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>example</groupId>
<artifactId>storecard</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>StoreCard</name>
<description>StoreCard service for woodland water store</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

	&lt;dependency&gt;
		&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
		&lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
		&lt;scope&gt;test&lt;/scope&gt;
	&lt;/dependency&gt;

<!-- -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jdbc</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
<version>2.2.3</version>
</dependency>

	&lt;!--		&lt;dependency&gt;--&gt;

<!-- <groupId>com.h2database</groupId>-->
<!-- <artifactId>h2</artifactId>-->
<!-- <scope>runtime</scope>-->
<!-- </dependency>-->

&lt;/dependencies&gt;

&lt;build&gt;
	&lt;plugins&gt;
		&lt;plugin&gt;
			&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
			&lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
		&lt;/plugin&gt;
	&lt;/plugins&gt;
&lt;/build&gt;

</project>










Reading through the output I noticed 2 things


ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'storeCardController': Unsatisfied dependency expressed through field 'storeCardRepository': No qualifying bean of type 'example.storecard.StoreCardRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}


and


Field storeCardRepository in example.storecard.StoreCardController required a bean of type 'example.storecard.StoreCardRepository' 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 'example.storecard.StoreCardRepository' in your configuration.


I can guess that this is saying that something is wrong with my repository class and spring boot not being able to make a bean for it for some reason. But since that is the extent of my knowledge with spring boot all I can do is google and see if there is another post out there that might solve my issue but I&#39;ve found nothing so far after trying many possible solutions.



</details>


# 答案1
**得分**: 3

In the pom.xml file remove this:


org.springframework.data
spring-data-jdbc


jakarta.persistence
jakarta.persistence-api
2.2.3

```

Add following instead:

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

Change the repository interface to extend JpaRepository like this:

public interface StoreCardRepository extends JpaRepository<StoreCard, Long> {
}

The entity class can't be a Java record. It should be a Java bean (POJO) with mandatory getters, setters and no-args constructor. Something like this:

@Entity
@NoArgsConstructor
@Getter
@Setter
@ToString
public class StoreCard {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private BigDecimal amount;
}

Please note: the annotations for getters and setters etc come from Lombok. Very helpful plugin. Otherwise you will need to implement it yourself.

英文:

In the pom.xml file remove this:

&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.data&lt;/groupId&gt;
    &lt;artifactId&gt;spring-data-jdbc&lt;/artifactId&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;jakarta.persistence&lt;/groupId&gt;
    &lt;artifactId&gt;jakarta.persistence-api&lt;/artifactId&gt;
    &lt;version&gt;2.2.3&lt;/version&gt;
&lt;/dependency&gt;

Add following instead:

&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
&lt;/dependency&gt;

Change the repository interface to extend JpaRepository like this:

public interface StoreCardRepository extends JpaRepository&lt;StoreCard, Long&gt; {
}

The entity class can't be a Java record. It should be a Java bean (POJO) with mandatory getters, setters and no-args constructor. Something like this:

@Entity
@NoArgsConstructor
@Getter
@Setter
@ToString
public class StoreCard {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private BigDecimal amount;
}

Please note: the annotations for getters and setters etc come from Lombok. Very helpful plugin. Otherwise you will need to implement it yourself.

答案2

得分: 1

你似乎缺少包含数据源自动配置的JPA依赖项

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

It seems that you are missing the jpa dependency which contains the autoconfigure for your datasource

&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
&lt;/dependency&gt;

huangapple
  • 本文由 发表于 2023年5月10日 15:10:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76215778.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定