您可以创建一个配置类,在其中根据您的环境跟踪实际 id 并使用 jackson 的 @JsonAnyGetter 映射它们。
例如,如果您有以下application.properties(我在这里使用multi-document props,但您也可以在每个配置文件中使用application.properties):
spring.profiles.active=dev
#---
spring.config.activate.on-profile=dev
application.requestClass.nameId=123
#---
spring.config.activate.on-profile=test
application.requestClass.nameId=456
然后,您将创建您的配置类(我使用 Lombok 的 @Data 作为 getter/setter):
@Configuration
@Data
public class RequestClassConfig {
@Value("${application.requestClass.nameId}")
private String nameId;
@PostConstruct
public void postConstruct() {
RequestClass.config = this;
}
}
最后是你的 DTO,@JsonAnyGetter:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class RequestClass {
public static RequestClassConfig config;
@JsonIgnore
private String name;
@JsonAnyGetter
public Map<String, Object> any() {
final var map = new HashMap<String, Object>();
map.put(config.getNameId(), this.name);
return map;
}
}
请注意,您可以对其余的道具执行相同的操作,为简洁起见,我省略了这些。
现在进行快速测试:
@SpringBootApplication
public class App {
public static void main(String[] args) throws JsonProcessingException {
SpringApplication.run(App.class, args);
final var mapper = new ObjectMapper();
final var req = new RequestClass();
req.setName("test");
System.out.println(mapper.writeValueAsString(req));
}
}
这将打印
如果dev 配置文件处于活动状态,则{"123":"test"} 到控制台
和
{"456":"test"} 如果test 配置文件处于活动状态。