在 Netflix Feign 中,@Body 注解用于指定一个方法参数作为 HTTP 请求的主体内容。它允许你将一个 Java 对象转换为合适的格式(如 JSON、XML 等)并作为请求体发送到目标服务端点。这在进行 POST、PUT 等需要发送请求体的 HTTP 操作时非常有用,能够清晰地定义请求数据的来源。
假设有一个服务接受一个 User 实体,并且返回一个 User 实体。步骤如下:
(1)定义 User 实体
@Data
@Builder
@ToString
public class User {
private Long id;
private String name;
private Integer age;
public User() {}
public User(Long id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
}(2)服务接口
@PostMapping("/body2")
public User body2(@RequestBody User user) {
return user;
}(3)定义 Feign 客户端
@RequestLine("POST /simple/body2")
@Headers("Content-Type: application/json")
@Body("{body}")
User body2(User user);注意,如果要传递和接受对象,我们需要在通过 create() 方法创建 Feign 客户端中定义 Encoder 和 Decoder,如下:
static SimpleFeign createJson() {
return Feign.builder()
.encoder(new JacksonEncoder())
.decoder(new JacksonDecoder())
.contract(new Contract.Default())
.target(SimpleFeign.class, "http://localhost:8090");
}(4)调用 Feign 客户端
@GetMapping("/")
public String index() {
return SimpleFeign.createJson().body2(User.builder().id(100L).name("Tom").age(20).build()).toString();
}输出结果如下:

下面是 @Body 注解源码:
package feign;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Body {
String value();
}在 @Body 注解中,value 是唯一的一个属性,其返回值类型为 String。当我们在方法上使用 Body 注解时,通过给 value 属性赋值,就可以指定该方法所发起的 HTTP 请求体的内容。例如:
@RequestLine("POST /simple/body2")
@Headers("Content-Type: application/json")
@Body("{\"id\":100, \"name\":\"Tom\", \"age\":20}")
User body3();当然,也可以通过“{变量}”的方式:
@RequestLine("POST /simple/body2")
@Headers("Content-Type: application/json")
@Body("{body}")
User body2(User user);