java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot 接口统一前缀

SpringBoot实现接口统一前缀

作者:catoop

本文主要介绍了SpringBoot实现接口统一前缀,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

需求

需求如题,想给一个 spring boot 项目的所有请求路径添加统一前缀,可以通过 context-path 来配置。但是在同时存在静态资源和 Controller 接口的项目中,如果希望静态资源从根路径访问,并且所有接口拥有统一路径前缀,则需要通过 Spring 层面来解决这个问题(context-path 是 web 容器层面的,如果配置它则会把静态资源都包含进去)。

如下接口示例:

# 3个静态资源
http://localhost:8080/index.html
http://localhost:8080/home.js
http://localhost:8080/dog.png

# 3个统一前缀为 /api
http://localhost:8080/api/test/show
http://localhost:8080/api/test/display
http://localhost:8080/api/test/print

如上URL示例中,希望放在 springboot 根目录 static 中的静态资源能直接通过根路径访问。其他 Controller 接口的前缀 “/api” 可以在配置文件中自定义配置变更。

实现

实现方法很简单,如下代码和配置文件:

1、GlobalControllerPathPrefixConfiguration.java

package com.example.demospringbean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
 * 为 Controller 接口配置统一前缀
 *
 * @author shanhy
 * @date 2023-03-20 15:50
 */
@Configuration
public class GlobalControllerPathPrefixConfiguration implements WebMvcConfigurer {
    @Value("${spring.controller.path-prefix:}")
    private String pathPrefix;
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.addPathPrefix(pathPrefix, c -> c.isAnnotationPresent(RestController.class));
    }
}

2、application.properties

spring.controller.path-prefix=/api

配置文件中参数 spring.controller.path-prefix 也可以是多级路径,例如 /api/demo。

3、TestController.java

/**
 * 接口示例
 * 
 * @author shanhy
 * @date 2023-03-20 15:49
 */
@RestController
@RequestMapping("/test")
public class TestController {
    @GetMapping("/show")
    public String show(){
        return "OK";
    }
}

最后将 dog.png 放在 springboot 项目的 static 目录中用来测试。

验证

打开浏览器分别访问如下路径可以正常显示结果,表示成功。

http://localhost:8080/dog.png
http://localhost:8080/api/test/show

到此这篇关于SpringBoot实现接口统一前缀的文章就介绍到这了,更多相关SpringBoot 接口统一前缀内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文