SpringBoot2为接口统一加url前缀

60 阅读1分钟

背景

有时候会面临前后端都放在一起的情况,这个时候我们就不好去使用配置中的 server.servlet.context-path ,经过一番查找,发现使用注解还是挺方便的。

解决办法

定义注解

package com.example.demo.annotation;

import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import java.lang.annotation.*;

/**
 * controller层统一使用该注解
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RestController
public @interface ApiRestController {
    /**
     * Alias for {@link Controller#value}.
     */
    @AliasFor(annotation = Controller.class)
    String value() default "";
}

实现 WebMvcConfigurer 配置路径前缀

package com.example.demo.config;


import com.example.demo.annotation.ApiRestController;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 配置统一的后台接口访问路径的前缀
 */
@Configuration
public class CustomWebMvcConfig implements WebMvcConfigurer {

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer
                .addPathPrefix("/api", c -> c.isAnnotationPresent(ApiRestController.class));
    }

}

Controller 类上使用注解

package com.example.demo.controller.api;

import com.example.demo.annotation.ApiRestController;
import org.springframework.web.bind.annotation.GetMapping;

@ApiRestController
@RequestMapping("/token")
public class UserTokenController {

    /**
     * 获取 user token
     */
    @GetMapping("/getUserToken")
    public ResponseBase getUserToken(HttpServletRequest request, HttpServletResponse response){
    }
}

全文参考:Java:SpringBoot给Controller添加统一路由前缀