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

微服务项目中@EntityScan注解无效报Not a managed type的解决方法

解决方案

1. 确保@EntityScan注解放在正确位置

将@EntityScan(basePackages = "com.example.product.entity")添加到Product服务的主启动类上,而非其他业务类。同时需配合@EnableJpaRepositories指定Repository的扫描范围,示例:

package com.example.product;

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.product.entity") // 扫描common服务中的实体类
@EnableJpaRepositories(basePackages = "com.example.computer.repository") // 扫描当前服务的Repository
public class ProductApplication {
    public static void main(String[] args) {
        SpringApplication.run(ProductApplication.class, args);
    }
}

注意:Spring Boot 3.x需导入org.springframework.boot.autoconfigure.domain.EntityScan,Spring Boot 2.x则使用org.springframework.data.jpa.repository.config.EntityScan,不要混淆。

2. 验证实体类的JPA注解配置

检查common服务中的Computer实体类是否正确标注核心JPA注解:

package com.example.product.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;

@Entity // 必须添加此注解,标记为JPA管理实体
public class Computer {
    @Id // 主键注解
    @GeneratedValue(strategy = GenerationType.IDENTITY) // 主键生成策略
    private Long id;
    // 其他业务字段、getter和setter方法
}

Spring Boot 3+使用jakarta.persistence包,Spring Boot 2.x使用javax.persistence包,不可混用。

3. 确认依赖引入的正确性

检查Product服务的依赖配置文件,确保common服务的依赖是运行时可见的:

  • Maven示例:
<dependency>
    <groupId>com.example</groupId>
    <artifactId>common-service</artifactId>
    <version>1.0.0</version>
    <!-- 禁止使用<scope>provided</scope>,否则运行时无法加载实体类字节码 -->
</dependency>
  • Gradle示例:
implementation 'com.example:common-service:1.0.0'

4. 清理缓存并重新构建

执行命令清理项目缓存并重新构建,避免依赖加载异常:

  • Maven:
mvn clean install
  • Gradle:
gradle clean build

完成后重启Product服务。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 11:20:37