Implementing Dictionary Text Mapping in Spring with Annotations and ResponseBodyAdvice

This article explains how to design a dictionary entity, create a custom annotation, and use Spring's ResponseBodyAdvice together with Java reflection to automatically convert enum values to their textual representations in API responses, improving front‑end display without manual mapping.

Architecture Digest
Architecture Digest
Architecture Digest
Implementing Dictionary Text Mapping in Spring with Annotations and ResponseBodyAdvice

When developing APIs, it is common to return enum values that the front‑end must translate into readable text. By letting the back‑end automatically set the textual description on the response object, the conversion problem is solved.

Entity Design

A simple Dict class represents a dictionary entry, with fields such as id, name, value, type, pid, status, sort, and description:

public class Dict {
    private String id;
    private String name;
    private String value;
    private String type;
    private String pid;
    private String status;
    private Integer sort;
    private String description;
}

Each row in the database corresponds to one Dict instance, and the type field distinguishes different dictionary categories.

Dictionary Text Mapping Example

{
  "code": "SUCCESS",
  "success": true,
  "message": "操作成功",
  "data": {
    "id": "1496108440362811394",
    "status": "DISABLE",
    "statusDesc": "禁用",
    ...
  }
}

Here status is the raw enum value, while statusDesc is its human‑readable text.

Defining a Dictionary Property Annotation

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface DictProperty {

    /**
     * Dictionary type
     */
    String type();

    /**
     * Name of the field that holds the enum value
     */
    String value();
}

The annotation stores the dictionary type and the name of the field that contains the enum value.

Usage Example

@Data
public class UserDTO {

    private String status;

    @DictProperty(type = "user_status", value = "status")
    private String statusDesc;
}

In UserDTO, status holds the enum code, and statusDesc will be filled with the corresponding text.

Implementation via ResponseBodyAdvice

Spring MVC provides ResponseBodyAdvice as a convenient hook to modify the response before it is written. By implementing this interface we can inspect the returned object, find fields annotated with DictProperty, look up the appropriate dictionary entry, and set the descriptive field.

public interface ResponseBodyAdvice<T> {
    boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType);
    @Nullable T beforeBodyWrite(@Nullable T body, MethodParameter returnType, MediaType selectedContentType,
                                 Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                 ServerHttpRequest request, ServerHttpResponse response);
}

The supports method decides whether the advice applies, and beforeBodyWrite performs the actual transformation.

Concrete advice implementation:

@Slf4j
@ControllerAdvice
public class DictResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Autowired
    private IDictService dictService;

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

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                 Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                 ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof Result) {
            handleBody(((Result) body).getData());
        } else if (body instanceof IPage) {
            handleBody(((IPage) body).getRecords());
        } else {
            handleBody(body);
        }
        return body;
    }
}

Inside handleBody (omitted for brevity) reflection is used to locate DictProperty annotations, retrieve the dictionary type, fetch the matching Dict entry via IDictService, and write the name value into the annotated field.

Further Considerations

Cache dictionary data to avoid repeated database queries and improve response time.

The same mapping logic could be applied without ResponseBodyAdvice by invoking a utility method directly on the object.

Additional optimizations and edge‑case handling can be added as needed.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaspringannotationresponsebodyadviceDictionary Mapping
Architecture Digest
Written by

Architecture Digest

Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.