You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot启动报错:找不到BookRepository类型Bean如何解决?

问题:Spring Boot启动时找不到BookRepository Bean

启动基于JPA和PostgreSQL的Spring Boot CRUD应用时,控制台报错:

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

Description:

Field bookRepo in com.arnab.controller.BookController required a bean of type 'com.arnab.repository.BookRepository' 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.arnab.repository.BookRepository' in your configuration.

项目结构

项目结构截图

相关代码与配置

启动类代码

package com.arnab.LibraryManagement;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@ComponentScan(basePackages = {"com.arnab.LibraryManagement","com.arnab.config","com.arnab.repository","com.arnab.controller","com.arnab.entity_Bean_DTO"})
public class LibraryManagementApplication {

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

}

Repository接口代码

package com.arnab.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.arnab.entity_Bean_DTO.Books;

@Repository
public interface BookRepository extends JpaRepository<Books, Long> 
{

}

Entity类代码

package com.arnab.entity_Bean_DTO;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "books")
public class Books 
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "bookid")
    private long id;
    
    @Column(name = "bookname")
    private String BookName;
    
    @Column(name = "genre")
    private String Genre;
    
    @Column(name = "author")
    private String Author;
    
    @Column(name = "availability_status")
    private String AvailabilityStatus;
    
    @Column(name = "price")
    private double price;
        
    public Books() {
        super();
    }

    public Books(long id, String bookName, String genre, String author, String availabilityStatus, double price) {
        super();
        this.id = id;
        BookName = bookName;
        Genre = genre;
        Author = author;
        AvailabilityStatus = availabilityStatus;
        this.price = price;
    }

    public long getId() {
        return id;
    }

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

    public String getBookName() {
        return BookName;
    }

    public void setBookName(String bookName) {
        BookName = bookName;
    }

    public String getGenre() {
        return Genre;
    }

    public void setGenre(String genre) {
        Genre = genre;
    }

    public String getAuthor() {
        return Author;
    }

    public void setAuthor(String author) {
        Author = author;
    }

    public String getAvailabilityStatus() {
        return AvailabilityStatus;
    }

    public void setAvailabilityStatus(String availabilityStatus) {
        AvailabilityStatus = availabilityStatus;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

Controller类代码

package com.arnab.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.arnab.entity_Bean_DTO.Books;
import com.arnab.repository.BookRepository;

@RestController
@RequestMapping("/library")
public class BookController 
{   
    @Autowired
    private BookRepository bookRepo;

    @RequestMapping(method = RequestMethod.GET, path = "/allBooks")
    public List<Books> findAllBook()
    {
        System.out.println("All books are = "+bookRepo.findAll());
        return bookRepo.findAll();
    }
    
    @RequestMapping(method = RequestMethod.POST, path = "/addBooks")
    public ResponseEntity<Books> addBooks(@RequestBody Books book)
    {
        Books saveBooks = bookRepo.save(book);
        System.out.println("Save books is = "+saveBooks);
        return new ResponseEntity<>(saveBooks,HttpStatus.CREATED);
    }
}

application.properties配置

#DATABASE PROPERTIES

spring.datasource.url=jdbc:postgresql://localhost:5432/library?currentSchema=library-management
spring.datasource.username=postgres
spring.datasource.password=root

# JPA PROPERTIES
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

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.7.15-SNAPSHOT</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.arnab</groupId>
    <artifactId>Library-Management</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Library-Management</name>
    <description>Library mnagement project for springboot </description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <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-starter-web-services</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.4.3</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <releases>
                <enabled>false</enabled>
            </releases>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <releases>
                <enabled>false</enabled>
            </releases>
        </pluginRepository>
    </pluginRepositories>

</project>

解决方案

问题核心是Spring未扫描到BookRepository并创建对应Bean,原因是启动类所在包com.arnab.LibraryManagement与Repository所在包com.arnab.repository不属于父子包,且Spring Data JPA的Repository扫描需额外配置。

方案1:添加@EnableJpaRepositories注解

在启动类上添加该注解并指定Repository所在包:

@SpringBootApplication
@ComponentScan(basePackages = {"com.arnab.LibraryManagement","com.arnab.config","com.arnab.repository","com.arnab.controller","com.arnab.entity_Bean_DTO"})
@EnableJpaRepositories(basePackages = "com.arnab.repository") // 新增配置
public class LibraryManagementApplication {
    public static void main(String[] args) {
        SpringApplication.run(LibraryManagementApplication.class, args);
    }
}

方案2:调整包结构(推荐)

将启动类移动到com.arnab根包下,@SpringBootApplication会自动扫描所有子包,无需额外配置@ComponentScan和@EnableJpaRepositories:

package com.arnab;

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

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

方案3:简化扫描配置

若不想调整包结构,可直接指定根包com.arnab,覆盖所有子包扫描:

@SpringBootApplication
@ComponentScan(basePackages = "com.arnab")
@EnableJpaRepositories(basePackages = "com.arnab")
public class LibraryManagementApplication {
    public static void main(String[] args) {
        SpringApplication.run(LibraryManagementApplication.class, args);
    }
}

执行任一方案后重启应用,Spring即可正确扫描并创建BookRepository的Bean,解决注入失败问题。


内容的提问来源于stack exchange,提问作者Abjava

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 20:17:33