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));
}
}