Home > Net >  How to send Spring Bean serialized as the body of a REST call using Web Client in a Java Spring boot
How to send Spring Bean serialized as the body of a REST call using Web Client in a Java Spring boot

Time:12-16

I need to make a REST call at regular intervals with same parameters every time, drawn from application properties. To avoid creating the request object every time, I want to use a Configuration Bean as request body which will be serialized to JSON.

The configuration bean looks like this:

@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. On making the REST call, during serialization I get the following error:

 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.post().body(Mono.just(configDetails), ConfigDetails.class)....

CodePudding user response:

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.

This worked but I am not sure if this can be considered a solution or just a 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.

@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;
    }
}
  • Related