In some cases, the prefixes in the service controller are consistent. For example, the prefix of all URLs is /context-path/api/v1, and you need to add it to some URLs. Uniform prefix.
The conceivable solution is to modify the context-path of the service and add api/v1 to the context-path. Modifying the global prefix in this way can solve the above problem, but there are drawbacks. If the URL has multiple prefixes , for example, some URLs need to be prefixed with api/v2, so they cannot be distinguished. If some static resources in the service do not want to add api/v1, they cannot be distinguished.
The following implements the unified addition of certain URL prefixes through custom annotations.
If you need multiple prefixes, add multiple sets of configurations, for example, add: api.prefix.v2=/api/v2
url prefix configuration
2. Configure mapped entities
@Data @Component @ConfigurationProperties(prefix = "api.prefix") public class ApiPrefix { private String v1; }
This annotation function is consistent with
@RestControllerand corresponds to For the configuration of api.prefix.v1, if there are multiple sets of configurations, just define multiple annotations
@RestController @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface ApiV1RestController { }
@AutoConfiguration public class WebMvcConfig implements WebMvcConfigurer { @Autowired private ApiPrefix apiPrefix; @Override public void configurePathMatch(PathMatchConfigurer configurer) { configurer.addPathPrefix(apiPrefix.getV1(), c -> c.isAnnotationPresent(ApiV1RestController.class)); } }
@ApiV1RestController @RequestMapping("/test/apiv1") public class TestApiV1RestController { @GetMapping() public ResponseEntity get() { return new ResponseEntity(); } }
The above is the detailed content of How to add URL prefix to SpringBoot multiple controllers. For more information, please follow other related articles on the PHP Chinese website!