完成一个 Demo
public class User implements Serializable {
private int id;
private String name;
// 省略构造方法、Getter和Setter
@Override
public String toString() {
return id + ":" + name;
}
}
@GetMapping("/users")
public List<User> list() {
return IntStream.rangeClosed(1, 10)
.mapToObj(i -> new User(i, "User" + i))
.collect(Collectors.toList());
}
http://localhost:8080/users
地址获取到一个包含十个用户信息的用户列表。public interface UserApiService {
@GetExchange("/users")
List<User> getUsers();
}
@Test
void getUsers() {
WebClient client = WebClient.builder().baseUrl("http://localhost:8080/").build();
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builder(WebClientAdapter.forClient(client)).build();
UserApiService service = factory.createClient(UserApiService.class);
List<User> users = service.getUsers();
for (User user : users) {
System.out.println(user);
}
}
1:User1
2:User2
...
9:User9
10:User10
GetExchange(HttpExchange)注解
spring-web
模块的org.springframework.web.service.annotation
包下,除了 HttpExchange 之外,其他的几个都是 HttpExchange 的特殊形式,这一点与 Spring MVC 中的 RequestMapping/GetMapping 等注解非常相似。@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
@Reflective(HttpExchangeReflectiveProcessor.class)
public @interface HttpExchange {
@AliasFor("url")
String value() default "";
@AliasFor("value")
String url() default "";
String method() default "";
String contentType() default "";
String[] accept() default {};
}
UserApiService 实例的创建
createClient
方法的源码中看到一些与创建 AOP 代理相似的代码,因此,我推测 Spring 之后可能会增加类似的注解来方便地创建代理对象。