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

Spring Boot项目中自动生成的REST端点来源及正确移除方法

关于Spring Boot中自动生成的REST端点问题解析

问题描述

开发学校项目的REST API时,访问根路径/返回了未手动创建的端点列表,包括/users、/profile等:

{
  "_links" : {
    "users" : {
      "href" : "http://localhost:8081/users{?page,size,sort}",
      "templated" : true
    },
    "kits" : {
      "href" : "http://localhost:8081/kits{?page,size,sort}",
      "templated" : true
    },
    "carts" : {
      "href" : "http://localhost:8081/carts{?page,size,sort}",
      "templated" : true
    },
    "profile" : {
      "href" : "http://localhost:8081/profile"
    }
  }
}

不想用requestMatcher("/users").denyAll()这种粗暴方式,需要明确这些端点的来源及正确移除方法。

端点来源分析

这些自动生成的端点并非来自Spring Security,而是Spring Data REST组件的默认行为:

  • /users、/kits、/carts:只要项目中存在继承JpaRepository(或Spring Data其他Repository接口)的类(比如UserRepository),Spring Data REST就会自动为其生成标准的RESTful端点,支持分页、排序等功能,这就是返回结果中带有{?page,size,sort}模板参数的原因。
  • /profile:这是Spring Data REST提供的元数据端点,用于暴露所有Repository的接口信息、支持的媒体类型等。

正确的移除/禁用方式

1. 完全禁用所有自动生成的端点

如果项目不需要Spring Data REST的自动生成功能,直接从pom.xml中移除对应的依赖:

<!-- 删除该依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>

2. 禁用指定Repository的端点

若仍需保留Spring Data REST,但要禁用某个特定Repository的自动端点,在对应的Repository接口上添加@RepositoryRestResource(exported = false)注解:

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(exported = false)
public interface UserRepository extends JpaRepository<User, Long> {
    // 自定义方法...
}

同理,对KitRepository、CartRepository执行相同操作,即可移除对应的/kits、/carts端点。

3. 禁用/profile元数据端点

通过配置文件关闭端点发现功能:

  • 使用application.properties:
spring.data.rest.discovery.enabled=false
  • 使用application.yml:
spring:
  data:
    rest:
      discovery:
        enabled: false

4. 自定义端点根路径(可选)

如果想保留自动生成的端点但避免路径冲突,可配置统一的根路径:

  • 使用application.properties:
spring.data.rest.base-path=/api

配置后,所有自动生成的端点会变为/api/users、/api/profile等。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 08:00:55