Spring Boot 字段topicRepository中需要的bean类型找不到

23c0lvtd  于 2023-06-05  发布在  Spring
关注(0)|答案(2)|浏览(100)

我正在学习this javaBrains的spring Boot 教程
到目前为止都做得很好。但是,当我创建了TopicRepository接口并对TopicServices中的方法进行了一两次更改时,在运行应用程序时突然弹出了这个错误:

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

Description:

Field topicRepository in com.myName.springboot.demo.springbootDb.rest.TopicService required a bean of type 'com.myName.springboot.demo.springbootDb.rest.TopicRepository' 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.myName.springboot.demo.springbootDb.rest.TopicRepository' in your configuration.

这是我的文件结构:

SpringbootDb应用程序:

package com.myName.springboot.demo.springbootDb;

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

@SpringBootApplication
public class SpringbootDbApplication {

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

}

FunRestController:

package com.myName.springboot.demo.springbootDb.rest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
public class FunRestController {

    @Autowired
    private TopicService topicService;

    @RequestMapping("/topics")
    public List<Topic> getAllTopics(){
        return topicService.getAllTopics();
    }

    @RequestMapping("/topics/{id}")
    public Topic getTopic(@PathVariable String id){
        return topicService.getTopic(id);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/topics")
    public void addTopic(@RequestBody Topic newTopic){
        topicService.addTopic(newTopic);
    }

    @RequestMapping(method = RequestMethod.PUT, value = "/topics/{id}")
    public void updateTopic(@RequestBody Topic newTopic, @PathVariable String id){
        topicService.updateTopic(newTopic, id);
    }

    @RequestMapping(method = RequestMethod.DELETE, value = "/topics/{id}")
    public void deleteTopic(@PathVariable String id){
        topicService.deleteTopic(id);
    }

    // expose '/' that returns "hello World"
    @GetMapping("/")
    public String sayHello(){
        return "Hello World";
    }

    @GetMapping("/workout")
    public String getDailyWorkout(){
        return "run";
    }

    // expose a new endpoint for frotune
    @GetMapping("/fortune")
    public String getDailyFortune(){
        return "lucky day";
    }

    @GetMapping("/test")
    public String get(){
        return "test";
    }
}

主题类:

package com.myName.springboot.demo.springbootDb.rest;

import jakarta.persistence.Entity;
import jakarta.persistence.Id;

@Entity
public class Topic {

    @Id
    private String id;
    private String name;
    private String description;

    public Topic() {
    }
    public Topic(String id, String name, String description) {
        this.id = id;
        this.name = name;
        this.description = description;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

}

主题服务:

package com.myName.springboot.demo.springbootDb.rest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
//@Repository
public class TopicService {

    @Autowired
    private TopicRepository topicRepository;

    private List<Topic> topics = new ArrayList<>(Arrays.asList(
            new Topic("spring", "Spring Framework", "SF Description"),
            new Topic("java", "Core Java", "cj Description"),
            new Topic("javascript", "Java script", "js Description")
    ));

    public List<Topic> getAllTopics(){
        // for databse connection
        // connects to the db, runs a query to get all the topics, convert each row into Topic instances, and get it back as an iterable list
        List<Topic> topics = new ArrayList<>();
        topicRepository.findAll()
                .forEach(topics::add);
        return topics;

        // for harcoded list
        //return topics;
    }

    public Topic getTopic(String id){
        for(Topic x: topics){
            if(x.getId().equals(id)) return x;
        }
        return new Topic("hi", "hi", "hi");
    }

    public void addTopic(Topic newTopic) {

        topicRepository.save(newTopic);

        //topics.add(newTopic);
    }

    public void updateTopic(Topic newTopic, String id) {
        for(int i  =0; i<topics.size(); i++) {
            Topic currTopic = topics.get(i);
            if (currTopic.getId().equals(id)) {
                topics.set(i, newTopic);
                return;
            }
        }
    }

    public void deleteTopic(String id) {
        for(int i  =0; i<topics.size(); i++) {
            Topic currTopic = topics.get(i);
            if (currTopic.getId().equals(id)) {
                topics.remove(i);
                return;
            }
        }
    }
}

TopicRepository:

package com.myName.springboot.demo.springbootDb.rest;

import com.myName.springboot.demo.springbootDb.rest.Topic;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

//@Repository
public interface TopicRepository extends CrudRepository<Topic, String> {

}

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.1.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.myName.springboot.demo</groupId>
    <artifactId>springbootDb</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springbootDb</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.apache.derby</groupId>
            <artifactId>derby</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.properties 文件:

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

从依赖关系中可以看出,在本例中,我尝试使用ApacheDerby数据库。
我已经尝试从我的服务类中的存储库示例中删除Autowired注解... doesn 't work...告诉我这个.topicRepository是null。我已经尝试以各种方式将@service @repository添加到服务类和控制器中......不起作用甚至我的文件结构对我来说似乎没问题
我想我的主类是无法定位的TopicRepository接口,但如何是可能的,我不知道,因为一切都工作得很好,在此之前。
请帮帮我

bpsygsoo

bpsygsoo1#

在SpringbootDbApplication主类中添加@EnableJpaRepositories,并在TopicRepository接口中取消注解@Repository

@EnableJpaRepositories(basePackages = 
{"com.myName.springboot.demo.springbootDb.rest"})
@SpringBootApplication
public class SpringbootDbApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootDbApplication.class, args);
    }
}
2izufjch

2izufjch2#

有两种方法可以解决这个问题。第一种方法是在@SpringBootApplication注解中使用scanBasePackages属性,如下所示:

@SpringBootApplication(scanBasePackages = { "com.example.something", 
"com.example.applicant" })

我已经解决了这个问题。默认情况下,@SpringBootApplication声明下的所有包都会被扫描。在本例中,假设带有@SpringBootApplication声明的主类ExampleApplication位于com.example.something包中,则将扫描com.example.something下的所有组件,而不会扫描com.example.applicant。这将确保扫描所有指定的组件。但是,如果应用程序的规模增长,这种方法可能会变得很麻烦。
我选择的第二种方法是重组一揽子计划。我重新整理了包如下:

src/
├── main/
│   └── java/
|       ├── com.example/
|       |   └── Application.java
|       ├── com.example.model/
|       |   └── User.java
|       ├── com.example.controller/
|       |   ├── IndexController.java
|       |   └── UsersController.java
|       └── com.example.service/
|           └── UserService.java
└── resources/
    └── application.properties

这种新的包结构允许更有组织和可扩展的包管理方法。现在,应用程序将自动扫描其各自包中的组件,而无需显式配置。
希望会有帮助

相关问题