【问题标题】:Exception:Field studentRepository in com.example.demo.cotroller.StudentController required a bean of type 'com....Repository' that could not be found例外:com.example.demo.cotroller.StudentController 中的字段 studentRepository 需要找不到类型为“com....Repository”的 bean
【发布时间】:2021-11-16 10:47:26
【问题描述】:

我跟着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。因此,我搜索了很多方法来处理它。而且我不想添加新代码或新文件。正如网站在创建界面存储库时所说,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);
    }

}

学生.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   

解决了!

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

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

【问题讨论】:

  • @DhwanilPatel 非常感谢!我真的从你身上学到了很多:)
  • @DhwanilPatel 将您的 cmets 添加为答案,以便对其进行投票、接受和“关闭”问题;)
  • 好的,但是学习和帮助比投票更重要。谢谢你们俩。 :)

标签: mysql spring-boot exception javabeans autowired


【解决方案1】:

是的,你是对的 spring 在他们身边执行存储库配置,但你必须通知 spring 你想要执行哪个类或包含这个功能。为此,您必须在存储库类中添加 @Repository 注释。

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

此外,如果您使用多个类,如用户和部门,并且您希望执行任何操作,则仅发生服务之间的通信,而不是共享存储库对象

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    • 2020-10-28
    • 2019-07-20
    • 2020-06-16
    • 1970-01-01
    相关资源
    最近更新 更多