Exception:Field com.example.demo.cotroller.StudentController 中的 studentRepository 需要找不到类型 'com....Repository' 的 bean

Exception:Field studentRepository in com.example.demo.cotroller.StudentController required a bean of type 'com....Repository' that could not be found

我跟随 https://spring.io/guides/gs/accessing-data-mysql/#initial 和 MySQL 一起学习了 springboot。我遇到了如下错误。

2021-09-23 01:28:31.193  INFO 1196 --- [           main] com.example.demo.DemoApplication         : Starting DemoApplication using Java 1.8.0_144 on DESKTOP-PFH9867 with PID 1196 (C:\Users\Admin\IdeaProjects\demo\target\classes started by Admin in C:\Users\Admin\IdeaProjects\demo)
2021-09-23 01:28:31.196  INFO 1196 --- [           main] com.example.demo.DemoApplication         : No active profile set, falling back to default profiles: default
2021-09-23 01:28:33.014  INFO 1196 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2021-09-23 01:28:33.027  INFO 1196 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-09-23 01:28:33.027  INFO 1196 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.52]
2021-09-23 01:28:33.145  INFO 1196 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-09-23 01:28:33.146  INFO 1196 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1875 ms
2021-09-23 01:28:33.218  WARN 1196 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'studentController': Unsatisfied dependency expressed through field 'studentRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.demo.repository.StudentRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2021-09-23 01:28:33.221  INFO 1196 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2021-09-23 01:28:33.242  INFO 1196 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-09-23 01:28:33.269 ERROR 1196 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

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

Description:

Field studentRepository in com.example.demo.cotroller.StudentController required a bean of type 'com.example.demo.repository.StudentRepository' 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 'com.example.demo.repository.StudentRepository' in your configuration.


Process finished with exit code 1

很明显,主要问题是 @Autowired 在 Controller 中。因此,我搜索了很多方法来处理它。而且我不想添加新代码或新文件。正如网站在创建接口存储库时所说的那样,Spring automatically implements this repository interface in a bean that has the same name (with a change in the case — it is called userRepository). 因此,我不想添加新代码或文件。我认为问题出在我的 application.properties 或目录的相对位置。但它们根本不起作用。

而我的代码如下。

DemoApplication.java

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class  DemoApplication {

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

}

Student.java

package com.example.demo.entity;

import javax.persistence.Entity;

// https://spring.io/guides/gs/accessing-data-mysql/

@Entity // This tells Hibernate to make a table out of this class
public class Student {
    // 2147483647
    private Integer studentID;

    private String name;

    private String department;

    private String major;

    public Integer getStudentID() {
        return studentID;
    }

    public void setStudentID(Integer studentID) {
        this.studentID = studentID;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public String getMajor() {
        return major;
    }

    public void setMajor(String major) {
        this.major = major;
    }
}

StudentController.java

package com.example.demo.cotroller;

import com.example.demo.entity.Student;
import com.example.demo.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller // This means that this class is a Controller
@RequestMapping(path="/api/v1/student") // This means URL's start with /demo (after Application path)
public class StudentController {
    // This means to get the bean called studentRepository
    // Which is auto-generated by Spring, we will use it to handle the data
    @Autowired
    private StudentRepository studentRepository;

    @PostMapping(path="/add") // Map ONLY POST Requests
    public @ResponseBody
    String addNewUser (@RequestBody Student student) {
        // @ResponseBody means the returned String is the response, not a view name
        // @RequestParam means it is a parameter from the GET or POST request

        studentRepository.save(student);
        return "Saved";
    }
}

StudentRepository.java

package com.example.demo.repository;

import com.example.demo.entity.Student;
import org.springframework.data.repository.CrudRepository;

// This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository
// CRUD refers Create, Read, Update, Delete
public interface StudentRepository extends CrudRepository<Student, Integer> {
}

我的目录组织如下。

java
|--com.example.demo
   |--controller
      |--StudentController.java
   |--entity
      |--Student.java
   |--repository
      |--StudentRepository.java
   DemoApplication.java   

已解决!

终于找到真正的原因了!我太粗心了,无法按照教程进行操作。它说单击依赖项和 select Spring Web、Spring Data JPA 和 MySQL 驱动程序。但我没有点击 Spring Data JPA!

我在 IDEA 中通过 selecting Spring Web、Spring Data JPA 和 MySQL Driver 重新创建了项目,并复制了问题描述中描述的文件,那么问题就解决了。

是的,你是对的 spring 由他们执行存储库配置,但你必须通知 spring 你想在哪个 class 上执行或包含此功能。为此,您必须在存储库 class.

中添加 @Repository 注释

还有一件事供您参考。在任何语言中,结构都是任何编程语言的重要组成部分。要理解它,您始终必须遵循最佳实践。在这里,您直接在控制器中定义存储库 class,这是完全错误的。控制器仅用于控制即将到来的请求并将响应发送回给它们。所以,这种业务逻辑总是发生在你的服务 class 或 DAOImpl class 中。不要在其他 classes.

中定义数据库对象

此外,如果您与多个 类 一起工作,例如用户和部门,并且您只想执行任何操作,服务之间的通信不会共享存储库对象