springboot 给controller路径增加前缀
springboot-web在访问的时,全局增加访问前缀,需要自定义配置。如果使用webmvc需要实现WebMvcConfigurer的配置类并实现configurePathMatch方法,如果使用webfulx需要继承WebFluxConfigurer并实现configurePathMatching方式。2.2 webfulx下配置2.局部配置(只修改部分)2.1 自定义注解2.2control
·
springboot-web在访问的时,全局增加访问前缀,需要自定义配置。如果使用webmvc需要实现
WebMvcConfigurer的配置类并实现configurePathMatch方法,如果使用webfulx需要继承WebFluxConfigurer并实现configurePathMatching方式。
1.全局配置
1.1 webmvc下配置
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 MyWebConnfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.addPathPrefix("/api/v1", c -> true);
}
}
2.2 webfulx下配置
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.config.PathMatchConfigurer;
import org.springframework.web.reactive.config.WebFluxConfigurer;
@Configuration
public class MyWebConnfig implements WebFluxConfigurer {
@Override
public void configurePathMatching(PathMatchConfigurer configurer) {
configurer.addPathPrefix("/api/v1", c -> true);
}
}
2.局部配置(只修改部分)
2.1 自定义注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@RestController
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public @interface ApiController {
@AliasFor(annotation = RequestMapping.class)
String name() default "";
@AliasFor(annotation = RequestMapping.class)
String[] value() default {};
@AliasFor(annotation = RequestMapping.class)
String[] path() default {};
}
2.2controller上增加注解使用
@ApiController("hello")
public class HelloController {
@GetMapping("info")
public String helloSay() {
return "hello say hello;";
}
}
2.2修改WebMvcConfigurer配置
@Configuration
public class MyWebConnfig implements WebMvcConfigurer {
// @Override
// public void configurePathMatch(PathMatchConfigurer configurer) {
// configurer.addPathPrefix("/api", c -> true);
// }
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.addPathPrefix("/api/v1", cls -> cls.isAnnotationPresent(ApiController.class));
}
}

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐

所有评论(0)