Spring boot指定context-path的两种方式

设置统一的api访问path路径,这里介绍两种常用方式

application.yml文件中直接指定path

yml文件中自带的配置,是全局统一设置的,设置完程序的api访问都要加上/proxy(这里可以随意指定)

具体配置参数如下
server:
  port: 8032
  servlet:
    context-path: /proxy #指定自己的path路径

当工程里不想用全局的context-path,我们可以通过实现WebMvcConfigurer方式来指定

1. 先自己写一个RestController注解

import org.springframework.core.annotation.AliasFor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.annotation.*;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RestController
@RequestMapping
public @interface OfficeRestController {

    @AliasFor(annotation = RequestMapping.class)
    String name() default "";

    @AliasFor(annotation = RequestMapping.class)
    String[] value() default {};

    @AliasFor(annotation = RequestMapping.class)
    String[] path() default {};

}

2. 写完注解,我们再写一个实现WebMvcConfigurer类

import io.hcbm.common.annotation.OfficeRestController;
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 ProxyWebMvcConfig implements WebMvcConfigurer {

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        //如果controller上有OfficeRestController注解,就替换path路径
        configurer

                .addPathPrefix("/office", c -> c.isAnnotationPresent(OfficeRestController.class));
    }

}

3. controller层写法

注意controller层不需要再次注入@RestController,@RequestMapping

import io.hcbm.common.annotation.OfficeRestController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@OfficeRestController("/v1/wps")
@Slf4j
public class WpsController {

    @GetMapping("/edit/view")
    public ResponseEntity getEditUrl() {
        return ResponseEntity.ok("test...");
    }
}

posted @ 2022-08-26 16:32  Levcon  阅读(6719)  评论(0编辑  收藏  举报