彩票网站建设开发新发布的新闻
网上的文章五花八门,不写SpringBoot的版本号,导致代码拿来主义不好使了。
本文采用的版本
SpringBoot 2.7.7
Java 1.8
目录
- 1、默认访问路径
- 2、整个项目增加路由前缀
- 3、通过注解方式增加路由前缀
- 4、按照目录结构添加前缀
- 参考文章
1、默认访问路径
package com.example.demo.controller.api;import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/api")
public class AppIndexController {@GetMapping("/index")public String index() {return "app";}
}
访问地址:http://localhost:8080/api/index
2、整个项目增加路由前缀
application.yml
server:servlet:context-path: /prefix
访问地址:http://localhost:8080/prefix/api/index
注意:该方案会将所有的路由都增加一个前缀
3、通过注解方式增加路由前缀
注解
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 "";
}
配置
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 {@Overridepublic void configurePathMatch(PathMatchConfigurer configurer) {configurer.addPathPrefix("/api", c -> c.isAnnotationPresent(ApiRestController.class));}}
使用注解
package com.example.demo.controller.api;import com.example.demo.annotation.ApiRestController;
import org.springframework.web.bind.annotation.GetMapping;@ApiRestController
// @RestController
// @RequestMapping("/api")
public class AppIndexController {@GetMapping("/index")public String index() {return "app";}
}
访问地址:http://localhost:8080/api/index
4、按照目录结构添加前缀
没有成功,可能是版本的问题
Neither PathPatterns nor String patterns condition
参考文章
- SpringBoot2.x 给Controller的RequestMapping添加统一前缀
- SpringBoot - 根据目录结构自动生成路由前缀