Spring中如何用@ConfigurationProperties实现属性名自定义映射(不改字段名)
Spring Boot配置属性映射方案
要在不修改字段名称的前提下完成属性映射,直接借助Spring Boot支持的注解即可实现,具体操作如下:
1. 修改配置类,添加映射注解
在BarcodeConfig类的对应字段上添加@JsonProperty注解(或Spring Boot 2.2+新增的@PropertyName注解),指定对应的属性键名:
import com.fasterxml.jackson.annotation.JsonProperty; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; // 若未通过其他方式注册配置类,需添加@Component让Spring扫描并托管 @Component @ConfigurationProperties(prefix = "user") public class BarcodeConfig { @JsonProperty("name") private String customName; @JsonProperty("details") private Details customDetails; // 必须提供标准getter/setter方法,才能完成属性绑定 public String getCustomName() { return customName; } public void setCustomName(String customName) { this.customName = customName; } public Details getCustomDetails() { return customDetails; } public void setCustomDetails(Details customDetails) { this.customDetails = customDetails; } // 内部类Details需包含对应属性的字段及getter/setter public static class Details { private String address; private String something; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getSomething() { return something; } public void setSomething(String something) { this.something = something; } } }
2. 注解作用说明
@JsonProperty("name"):告知Spring Boot将配置文件中user.name(类前缀为user,对应键为name)的值绑定到customName字段。@JsonProperty("details"):将配置文件中user.details.*层级的属性,递归绑定到customDetails对象,自动匹配内部类Details的对应字段。
3. 验证绑定效果
确保配置类被Spring容器托管后,可通过注入BarcodeConfig获取绑定的属性值:
@Autowired private BarcodeConfig barcodeConfig; // 测试输出示例 System.out.println(barcodeConfig.getCustomName()); // 输出sampleName System.out.println(barcodeConfig.getCustomDetails().getAddress()); // 输出sampleAddress
内容的提问来源于stack exchange,提问作者grzesiu988
相关产品推荐
相关产品推荐

