Response Handling in Spring with ResponseBodyAdvice

Manpreet Singh
3 min readMar 6

When building web applications with the Spring Framework, it’s common to need to modify the response sent back to the client. Spring provides an elegant way to do this through a feature called ResponseBodyAdvice. In this article, we’ll explore what ResponseBodyAdvice is, how it works, and how to use it in Java code.

What is ResponseBodyAdvice?

ResponseBodyAdvice is an interface provided by Spring that allows you to modify the response returned by a controller method before it is sent back to the client. It’s essentially an interceptor that can be used to add, remove, or modify the content of the response. It’s particularly useful for handling cross-cutting concerns such as adding custom headers, logging, or modifying the response payload.

How ResponseBodyAdvice works

The ResponseBodyAdvice interface has three methods:

  1. supports
  2. beforeBodyWrite
  3. afterCompletion

The supports method is used to specify the type of the response object that this advice applies to. The beforeBodyWrite method is called before the response is written to the output stream, and allows you to modify the response object. The afterCompletion method is called after the response has been written to the output stream.

Here’s an example of how ResponseBodyAdvice can be used to modify the response object:

public class CustomResponseBodyAdvice implements ResponseBodyAdvice<Object> {

public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;

public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
ServerHttpResponse response) {

// modify the response body here
// for example, add a custom header
response.getHeaders().add("Custom-Header", "Hello World");

return body;

public void afterCompletion(NativeWebRequest request, ModelMap model, Exception ex) throws Exception {
// do nothing

In this example, we’ve created a custom ResponseBodyAdvice class that applies to all response objects (specified by returning true in the supports

Manpreet Singh

Software developer who loves writing about programming, technology, passive income strategies etc.