nami - 使用 Solon 注解(新特性)
(v3.3.0 后支持),新的特性可以直接 copy 控制器上的代码(微做调整),即可作为客户端接口。
1、注解的对应关系
Nami 注解 | Solon 注解 | 备注 |
---|---|---|
@NamiMapping | @Mapping @Get 、@Put 、@Post 、@Delete 、@Patch | |
@Consumes | 申明请求的内容类型 | |
@NamiBody | @Body | 申明参数为 body(会转为独立主体发送) |
@NamiParam | @Param | |
@Header | 申明参数为 header(会自动转到请求头) | |
@Cookie | 申明参数为 cookie(会自动转到请求头) | |
@Path | 申明参数为 path(会自动转到url) |
注:@Path
将在 v3.3.1 后支持(落掉了)
2、尝试把 Nami 注解改为 Solon 注解
Nami 注解:
@NamiClient(url="http://localhost:8080/ComplexModelService/", headers="TOKEN=xxx")
public interface IComplexModelService {
//实际请求为:PUT http://localhost:8080/ComplexModelService/save
@NamiMapping("PUT")
void save(@Body ComplexModel model);
//实际请求为:GET http://localhost:8080/ComplexModelService/api/1.0.1?modelId=xxx
@NamiMapping("GET api/1.0.1")
ComplexModel read(Integer modelId);
}
(改为)Solon 注解:
@NamiClient(url="http://localhost:8080/ComplexModelService/", headers="TOKEN=xxx")
public interface IComplexModelService {
//实际请求为:PUT http://localhost:8080/ComplexModelService/save
@Put
void save(@NamiBody ComplexModel model);
//实际请求为:GET http://localhost:8080/ComplexModelService/api/1.0.1?modelId=xxx
@Get
@Mapping("api/1.0.1")
ComplexModel read(Integer modelId);
}
3、更丰富的 Solon 注解使用参考
@NamiClient
public interface HelloService {
@Post
@Mapping("hello")
String hello(String name, @Header("H1") String h1, @Cookie("C1") String c1);
@Consumes(MimeType.APPLICATION_JSON_VALUE)
@Mapping("/test01")
@Post
String test01(@Param("ids") List<String> ids);
@Mapping("/test02")
@Post
String test02(@Param("file") UploadedFile file);
@Mapping("/test03")
@Post
String test03();
@Mapping("/test04/{name}")
@Get
String test04(@Path("name") name); //v3.3.1 后支持 @Path 注解
}
简化模式(“路径段”与“方法”同名的、“参数名”相同的,可以简化):
@NamiClient
public interface HelloService {
@Post
String hello(String name, @Header("H1") String h1, @Cookie("C1") String c1);
@Consumes(MimeType.APPLICATION_JSON_VALUE)
@Post
String test01(List<String> ids);
@Post
String test02(UploadedFile file);
@Post
String test03();
@Mapping("/test04/{name}")
@Get
String test04(name);
}
进一步简化(有参数的默认是 "Post" 方式,没参数的默认是 "Get" 方式)
@NamiClient
public interface HelloService {
String hello(String name, @Header("H1") String h1, @Cookie("C1") String c1);
@Consumes(MimeType.APPLICATION_JSON_VALUE)
String test01(List<String> ids);
String test02(UploadedFile file);
@Post //如果是 Get 请求,这个注解可以去掉
String test03();
@Mapping("/test04/{name}")
@Get
String test04(name);
}