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

SpringBoot项目启动报错UnsatisfiedDependencyException求助

Spring Boot JPA 错误排查:Not a managed type: com.example.notesApp.model.Notes

我是Spring Boot新手,基于Maven搭建了Spring Boot-JPA-MySQL的Restful CRUD API项目OnlineNotes,在IntelliJ中运行时遭遇org.springframework.beans.factory.UnsatisfiedDependencyException错误,核心提示为Not a managed type: class com.example.notesApp.model.Notes。已尝试Stack Overflow上的相关解决方案,但问题仍未解决。以下是项目结构及相关代码文件,恳请帮忙排查解决:

项目结构

notesApp
├── src
│   ├── main
│   │   ├── java
│   │   │   ├── com
│   │   │   │   ├── example
│   │   │   │   │   ├── notesApp
│   │   │   │   │   │   ├── controller
│   │   │   │   │   │   │   ├── NoteController.java
│   │   │   │   │   │   ├── model
│   │   │   │   │   │   │   ├── Notes.java
│   │   │   │   │   │   ├── repository
│   │   │   │   │   │   │   ├── NoteRepository.java
│   │   │   │   │   │   ├── NotesAppApplication.java

相关代码文件

1. Model类 Notes.java

@Entity//Marks class as entity class for component scan
@Table (name = "notes")//Creates table named notes in DB
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt","updatedAt"}, allowGetters = true)//Makes variables un-editable for users by ignoring values if client provides in put/update service call

public class Notes implements Serializable {

    @Id//Defines upcoming var as primary key in table
    @GeneratedValue (strategy = GenerationType.IDENTITY)//Allows auto-increment for primary key
    private long id;

    @NotBlank
    private String title;

    @NotBlank
    private String content;

    @Column(nullable = false, updatable = false)//Defines column properties in DB
    @Temporal(TemporalType.TIMESTAMP)//Converts dates in appropriate formats in DB
    @CreatedDate
    private Date createdAt;

    @Column(nullable = false, updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @LastModifiedDate
    private Date updatedAt;
}

2. Repository类 NoteRepository.java

package com.example.notesApp.repository;

import com.example.notesApp.model.Notes;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository//Asks Spring to bootstrap the repository during component scan
public interface NoteRepository extends JpaRepository<Notes, Long> {

}

3. Controller类 NoteController.java

//Controller to create, retrieve, Update, delete a note
@RestController //Combination of @Controller and @ResponseBody
//@Controller defines this class is Controller to be bootstrapped while component scan
//@ResponseBody indicates the return value of method will be the response body
@RequestMapping(value = "/api")
//@RequestMapping defines the pattern of request URL
public class NoteController {


    @Autowired
    NoteRepository noteRepository;

    //Get all notes
    @GetMapping(value = "/notes")//@GetMapping handles the HTTP Get request and maps GET /notes/ URL to getAllNotes method
    public List<Notes> getAllNotes(){
        return noteRepository.findAll();
    }

    //Get a single note
    @GetMapping(value = "notes/{id}") //@GetMapping handles the HTTP Get request and maps GET /notes/{id} URL to getNotesById method
    public Notes getNotesById(@PathVariable(value = "id") long id){
        return noteRepository.findById(id).orElseThrow(()->new ResourceNotFoundException("Note","Id",id));

    }

    //Create a note
    @PostMapping (value = "/notes")//@PostMapping handles the HTTP POST request and maps POST /notes/ URL to createNote method
    public Notes createNote (@Valid @RequestBody Notes notes){
        //@Valid makes sure Request Body is valid as Title and Content of request is assigned to @NotNull annotation
        //@RequestBody binds request with method parameters
        return noteRepository.save(notes);
    }

    //Update a note
    @PutMapping(value = "notes/{id}")//@PutMapping handles the PUT request and maps PUT /notes/{Id} URl to updateNote method
    public Notes updateNote(@PathVariable(value = "id")long noteId, Notes UpdatedNote){
        Notes note = noteRepository.findById(noteId).orElseThrow(()->new ResourceNotFoundException("Note","Id",noteId));
        //Only Title and content are eligible for update
        note.setTitle(UpdatedNote.getTitle());
        note.setContent(UpdatedNote.getContent());

        return noteRepository.save(note);
    }

    //Delete a note
    @DeleteMapping(value = "notes/{id}")//@DeleteMapping handles DELETE request and maps DELETE notes/{id} to deleteNote method
    public void deleteNote(@PathVariable(value = "id")long id){
        Notes note = noteRepository.findById(id).orElseThrow(()-> new ResourceNotFoundException("Note","Id",id));
        noteRepository.delete(note);
    }
}

排查与解决步骤

1. 修正主启动类扫描范围

主类NotesAppApplication.java需显式指定实体和Repository的扫描包,确保Spring能识别到它们:

package com.example.notesApp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@EntityScan(basePackages = "com.example.notesApp.model")
@EnableJpaRepositories(basePackages = "com.example.notesApp.repository")
public class NotesAppApplication {
    public static void main(String[] args) {
        SpringApplication.run(NotesAppApplication.class, args);
    }
}

2. 完善实体类Notes.java

JPA实体类必须满足以下要求,否则无法被Spring管理:

  • 包含无参构造方法(JPA反射实例化必需)
  • 所有字段的getter/setter方法(JPA需要访问字段值)
  • 确保注解来自正确的包(Spring Boot 2.x用javax.persistence.*,3.x用jakarta.persistence.*)

完善后的实体类示例:

import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.io.Serializable;
import java.util.Date;

@Entity
@Table(name = "notes")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"}, allowGetters = true)
public class Notes implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @NotBlank
    private String title;

    @NotBlank
    private String content;

    @Column(nullable = false, updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @CreatedDate
    private Date createdAt;

    @Column(nullable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @LastModifiedDate
    private Date updatedAt;

    // 无参构造方法
    public Notes() {}

    // getter和setter方法
    public long getId() { return id; }
    public void setId(long id) { this.id = id; }

    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }

    public String getContent() { return content; }
    public void setContent(String content) { this.content = content; }

    public Date getCreatedAt() { return createdAt; }
    public Date getUpdatedAt() { return updatedAt; }
}

3. 验证Maven依赖配置

确保pom.xml中包含正确的JPA和MySQL驱动依赖,版本与Spring Boot匹配:

  • Spring Boot 2.x版本
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>
  • Spring Boot 3.x版本
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

4. 检查注解导入正确性

确认实体类中的@Entity、@Table、@Id等注解来自正确的包,避免导入其他框架的同名注解导致识别失败。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 15:00:53