Skip to content

Commit 9c109bf

Browse files
committed
修改java内容
1 parent 4614095 commit 9c109bf

File tree

3 files changed

+65
-1
lines changed

3 files changed

+65
-1
lines changed

Java/api自动增加前缀.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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+
![2](/img/java/api.png)
61+
62+
请求地址:http://localhost:8080/api/demo/a

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,6 @@
2323

2424
* [扫一扫登录](./webChat/扫一扫登录.md)
2525

26-
26+
# java
27+
* [api地址自动增加前缀](./Java/api自动增加前缀.md)
28+
* [springboot使用@value注入静态属性](./Java/Springboot使用@value注入静态属性.md)

img/java/api.png

2.78 KB
Loading

0 commit comments

Comments
 (0)