怎么把feign请求的interface在枚举里映射
时间: 2023-12-10 10:39:28 浏览: 78
可以在枚举中定义一个 `url` 字段,用于存储接口的 URL 地址。然后在定义每个枚举值时,将对应的 URL 地址赋值给该字段。例如:
```java
public enum MyApi {
GET_USER("/user/{id}", HttpMethod.GET),
ADD_USER("/user", HttpMethod.POST),
UPDATE_USER("/user/{id}", HttpMethod.PUT),
DELETE_USER("/user/{id}", HttpMethod.DELETE);
private String url;
private HttpMethod method;
MyApi(String url, HttpMethod method) {
this.url = url;
this.method = method;
}
public String getUrl() {
return url;
}
public HttpMethod getMethod() {
return method;
}
}
```
然后在使用 Feign 进行接口调用时,可以通过枚举值获取对应的 URL 地址和请求方法,然后使用 Feign 进行调用。例如:
```java
@FeignClient(name = "my-service")
public interface MyServiceClient {
@RequestMapping(method = RequestMethod.GET, value = MyApi.GET_USER.getUrl())
User getUser(@PathVariable("id") String id);
@RequestMapping(method = RequestMethod.POST, value = MyApi.ADD_USER.getUrl())
User addUser(@RequestBody User user);
@RequestMapping(method = RequestMethod.PUT, value = MyApi.UPDATE_USER.getUrl())
User updateUser(@PathVariable("id") String id, @RequestBody User user);
@RequestMapping(method = RequestMethod.DELETE, value = MyApi.DELETE_USER.getUrl())
void deleteUser(@PathVariable("id") String id);
}
```
这样就可以通过枚举来管理接口的 URL 地址,避免在代码中硬编码 URL,提高代码的可读性和可维护性。
阅读全文