[英]How to send Spring Bean serialized as the body of a REST call using Web Client in a Java Spring boot application?
I need to make a REST call at regular intervals with same parameters every time, drawn from application properties.我需要每次都使用相同的参数定期调用 REST,从应用程序属性中提取。 To avoid creating the request object every time, I want to use a Configuration Bean as request body which will be serialized to JSON.为了避免每次都创建请求 object,我想使用一个配置 Bean 作为请求主体,它将被序列化为 JSON。
The configuration bean looks like this:配置 bean 如下所示:
@ConfigurationProperties(prefix = "myprefix")
@Configuration("configname")
@Getter
@Setter
public class ConfigDetails {
private String c1;
private String c2;
private String c3;
}
And I inject this bean into the class calling the REST API with @Autowired
annotation.然后我将这个 bean 注入到 class 中,使用@Autowired
注释调用 REST API。 On making the REST call, during serialization I get the following error:在进行 REST 调用时,在序列化过程中出现以下错误:
No serializer found for class org.springframework.context.expression.StandardBeanExpressionResolver and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.ril.scm.node.data.PromiseEngineLoginDetails$$EnhancerBySpringCGLIB$$cad0a6e6["$$beanFactory"]->org.springframework.beans.factory.support.DefaultListableBeanFactory["beanExpressionResolver"])
I am using a WebClient to make the call like below:我正在使用 WebClient 进行如下调用:
webClient.post().body(Mono.just(configDetails), ConfigDetails.class)....
As a workaround, I tried creating a static non-bean copy of the Configuration Bean inside the class, copied the field value and used that static instance instead.作为解决方法,我尝试在 class 中创建配置 Bean 的 static 非 bean 副本,复制字段值并改用该 static 实例。
This worked but I am not sure if this can be considered a solution or just a hack!这行得通,但我不确定这是否可以被视为解决方案或只是一个 hack! The downside I can see is someone can forget to edit the init()
method at times there is a need to add a property.我看到的缺点是有人有时会忘记编辑init()
方法,有时需要添加属性。
@ConfigurationProperties(prefix = "myprefix")
@Configuration("configname")
@Getter
@Setter
public class ConfigDetails {
private String c1;
private String c2;
private String c3;
private static ConfigDetails staticConfigDetails;
@PostConstruct
public void init(){
staticConfigDetails = new ConfigDetails();
staticConfigDetails.setC1(this.c1);
...
//set other properties
....
}
public static ConfigDetails getInstance(){
return staticConfigDetails;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.