1 server.servlet.context-path=/xxx

这种方式是给项目所有请求加的全局路径,包括controller层的请求和静态文件的请求。

2 只对controller的后端接口请求生效,不对同一个项目中的竞态文件生效的方式如下:

PathConfig.java
/**
 * 配置统一的后台接口访问路径的前缀
 */
@Configuration
public class PathConfig implements WebMvcConfigurer {
    @Autowired
    private PathProperties pathProperties;
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer
                .addPathPrefix(pathProperties.globalPrefix,c -> c.isAnnotationPresent(RestController.class));
    }
}
PathProperties.java
/**
 * 接口路径前缀配置
 */
@Component
@ConfigurationProperties(prefix = "server.path")
@Data
public class PathProperties {
    String globalPrefix = "";
}

如果是jar包的话,需要通过spring的spi机制加载上面两个类:

spring.factories---只有是jar包被依赖时需要用到,如果直接在springboot项目中,不需要以下文件。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.ecej.cpcenter.common.config.PathConfig,\
com.ecej.cpcenter.common.config.PathProperties

最后在项目中依赖这个jar包,配置文件中添加对应的属性(server.path.globalPrefix=/test)就好了。这样加的路径只对controller的请求有效,对当前项目下的静态资源无效。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐