Zero‑Code Field Translation in SpringBoot 3 with Easy‑Trans
This article explains how the open‑source Easy‑Trans library can be integrated into SpringBoot 3 projects to automatically translate dictionary, association, and enum fields using a single annotation, eliminating repetitive code while maintaining high performance and minimal configuration.
1. Before and After Comparison
Integrating Easy‑Trans replaces verbose manual translation logic with a single annotation, drastically reducing code size and maintenance effort.
Before Integration
List<User> userList = userMapper.listUser();
List<Integer> statusList = userList.stream()
.map(User::getStatus)
.collect(Collectors.toList());
Map<Integer, String> statusMap = dictMapper.getDictMap("user_status", statusList);
userList.forEach(user -> user.setStatusName(statusMap.get(user.getStatus())));
// Additional loops for related data increase complexityAfter Integration
@Data
public class UserVO {
private Long id;
private String username;
@Trans(type = TransType.DICTIONARY, key = "user_status")
private Integer status;
private String statusName;
@Trans(type = TransType.SIMPLE, target = Role.class, refs = "userName")
private Long roleId;
private String createByName;
}The framework automatically translates fields at response time without modifying existing query logic, and the performance impact is negligible for typical workloads.
2. Prerequisites for SpringBoot 3 Integration
SpringBoot 3.1.12, JDK 17+, Maven, easy‑trans 3.1.4 (latest)
Applicable scenarios: dictionary translation, association table translation, enum translation, RPC translation in microservices
Key advantages: zero‑intrusion, Redis cache support, avoidance of N+1 queries, flexible configuration
Note: Versions above SpringBoot 3.2.x may cause startup exceptions; the examples use 3.1.12.
3. Maven Dependency
<properties>
<easy-trans.version>3.1.4</easy-trans.version>
</properties>
<!-- Core translation starter -->
<dependency>
<groupId>com.fhs-opensource</groupId>
<artifactId>easy-trans-spring-boot-starter</artifactId>
<version>${easy-trans.version}</version>
</dependency>
<!-- MyBatis‑Plus extension (optional, required for MP) -->
<dependency>
<groupId>com.fhs-opensource</groupId>
<artifactId>easy-trans-mybatis-plus-extend</artifactId>
<version>${easy-trans.version}</version>
</dependency>Gradle users can add the equivalent dependencies; no additional configuration is required.
4. Core Configuration (application.yml)
easy-trans:
is-enable-redis: true # Enable Redis cache; set false if not used
is-enable-global: true # Global translation intercepts all @ResponseBody
is-enable-tile: true # Enable flat‑mode translation
dict-use-redis: true # Store dictionary data in Redis (recommended for microservices)
is-enable-custom-rpc: true # Enable @RpcTrans for RPC translation
is-enable-map-result: true # Enable map‑result handling for specific frameworks
db-type: mysql # Database type for reverse translation
mp-new: true # Enable for MyBatis‑Plus 3.5.3.2+ versionsGlobal translation can be disabled for performance‑critical endpoints and replaced with method‑level @Trans.
Redis cache dramatically reduces dictionary lookup latency.
5. Four Common Scenarios
Scenario 1: Dictionary Translation (most common)
@Data
@TableName("sys_user")
public class User {
@TableId
private Long id;
private String username;
@Trans(type = TransType.DICTIONARY, key = "user_status")
private Integer status;
private String statusName; // Auto‑filled, no manual set required
}Initialize dictionary data:
@Autowired
private DictionaryTransService dictionaryTransService;
Map<String, String> transMap = new HashMap<>();
transMap.put("0", "禁用");
transMap.put("1", "启用");
dictionaryTransService.refreshCache("user_status", transMap);Scenario 2: Associated Table Translation
@Data
public class OrderVO {
private Long orderId;
private String orderNo;
@Trans(type = TransType.SIMPLE, target = UserVO.class)
private Long userId; // Service method will fetch username
private String userName; // Filled automatically
}Scenario 3: Enum Translation
public enum UserSexEnum {
man(1, "男"),
woman(0, "女");
private Integer type;
private String desc;
public String getDesc() { return desc; }
UserSexEnum(Integer type, String desc) { this.type = type; this.desc = desc; }
public static UserSexEnum getEnum(Integer type) {
for (UserSexEnum e : values()) {
if (e.type.equals(type)) return e;
}
return null;
}
}
@Data
public class UserVO {
private Integer gender;
@Trans(type = TransType.ENUM, key = "desc")
private UserSexEnum sexEnum;
public UserSexEnum getSexEnum() {
return gender != null ? UserSexEnum.getEnum(gender) : sexEnum;
}
}Scenario 4: Partial Translation (Performance‑First)
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@Trans // Enable translation only for this endpoint
@GetMapping("/list")
public List<UserVO> listUser() {
return userService.listUserVO();
}
}6. Production Performance Optimisation Tips
Force Redis cache for dictionary data and set appropriate TTL to avoid cache avalanche.
For interfaces returning >1000 rows, disable global translation and use method‑level @Trans.
Batch query associated data in the service layer to avoid per‑row database calls.
Keep flat‑mode disabled in production to improve response speed.
7. Summary
The lightweight open‑source Easy‑Trans tool fits seamlessly into the SpringBoot 3 ecosystem, providing automatic, zero‑intrusive field translation for dictionaries, associated tables, and enums. It eliminates repetitive manual code, incurs negligible runtime overhead, and can be adopted quickly in both new and legacy projects to boost development efficiency and maintain clean codebases.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
