|
| 1 | +* AutoPrefixUrlMapping.java |
| 2 | +```java |
| 3 | +public class AutoPrefixUrlMapping extends RequestMappingHandlerMapping { |
| 4 | + |
| 5 | + @Value("${api-package}") |
| 6 | + private String apiPackagePath; |
| 7 | + |
| 8 | + @Override |
| 9 | + protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) { |
| 10 | + RequestMappingInfo mappingInfo = super.getMappingForMethod(method, handlerType); |
| 11 | + if(mappingInfo != null){ |
| 12 | + String prefix = this.getPrefix(handlerType); |
| 13 | + return RequestMappingInfo.paths(prefix).build().combine(mappingInfo); |
| 14 | + } |
| 15 | + return mappingInfo; |
| 16 | + } |
| 17 | + |
| 18 | + private String getPrefix(Class<?> handlerType){ |
| 19 | + String packageName = handlerType.getPackage().getName(); |
| 20 | + String dotPath = packageName.replaceAll(this.apiPackagePath,""); |
| 21 | + return dotPath.replace(".", "/"); |
| 22 | + } |
| 23 | +} |
| 24 | +``` |
| 25 | + |
| 26 | +* AutoPrefixConfiguration.java |
| 27 | +```java |
| 28 | + |
| 29 | +@Configuration |
| 30 | +public class AutoPrefixConfiguration implements WebMvcRegistrations { |
| 31 | + |
| 32 | + @Override |
| 33 | + public RequestMappingHandlerMapping getRequestMappingHandlerMapping() { |
| 34 | + return new AutoPrefixUrlMapping(); |
| 35 | + } |
| 36 | +} |
| 37 | +``` |
| 38 | + |
| 39 | + |
| 40 | +* application.yml |
| 41 | + |
| 42 | +```yml |
| 43 | + api-package: com.example.demo |
| 44 | +``` |
| 45 | +* DemoController |
| 46 | +
|
| 47 | +```java |
| 48 | +@RestController |
| 49 | +@RequestMapping("/demo") |
| 50 | +public class DemoController { |
| 51 | + |
| 52 | + @GetMapping("/a") |
| 53 | + public ResponseEntity getUser() { |
| 54 | + return ResponseEntity.status(HttpStatus.OK).body("22"); |
| 55 | + } |
| 56 | + |
| 57 | +``` |
| 58 | + * 目录结构 |
| 59 | + |
| 60 | +  |
| 61 | + |
| 62 | +请求地址:http://localhost:8080/api/demo/a |
0 commit comments