SpringBoot接口請求入?yún)⒑统鰠⒃鰪姷奈宸N方法
在Spring Boot , Spring Cloud中,對接口的請求入?yún)⒑统鰠⑦M(jìn)行自定義的序列化和反序列化增強,通常有以下幾種方法:
1. 使用@JsonSerialize和@JsonDeserialize注解
可以在實體類的字段上使用這兩個注解來指定自定義的序列化器和反序列化器。
使用場景:
- 當(dāng)需要對某個特定字段進(jìn)行自定義的序列化和反序列化時。
- 當(dāng)實體類中的某些字段類型不是標(biāo)準(zhǔn)的JSON類型,需要轉(zhuǎn)換成JSON能識別的格式時。
- 需要在序列化和反序列化過程中添加自定義邏輯,如加密、解密、格式轉(zhuǎn)換等。
首先,定義自定義的序列化器和反序列化器:
public class CustomLocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
@Override
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeString(value.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
}
}
public class CustomLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
@Override
public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
return LocalDateTime.parse(p.getValueAsString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
}
然后,在實體類中使用這些注解:
public class MyEntity {
@JsonSerialize(using = CustomLocalDateTimeSerializer.class)
@JsonDeserialize(using = CustomLocalDateTimeDeserializer.class)
private LocalDateTime dateTime;
// getters and setters
}
2. 全局配置Jackson的ObjectMapper
通過配置ObjectMapper來全局地改變序列化和反序列化的行為,可以添加自定義的模塊或配置屬性。
使用場景:
- 當(dāng)項目中多個實體類需要應(yīng)用相同的序列化和反序列化規(guī)則時。
- 需要在全局范圍內(nèi)統(tǒng)一處理日期、時間、枚舉等類型的序列化和反序列化。
- 需要對
ObjectMapper進(jìn)行全局的配置,如設(shè)置默認(rèn)的時區(qū)、日期格式等。
創(chuàng)建一個自定義模塊,并注冊序列化器和反序列化器:
public class CustomJacksonModule extends SimpleModule {
public CustomJacksonModule() {
addSerializer(LocalDateTime.class, new CustomLocalDateTimeSerializer());
addDeserializer(LocalDateTime.class, new CustomLocalDateTimeDeserializer());
}
}
然后,配置ObjectMapper:
@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
return builder -> {
builder.modules(new CustomJacksonModule());
};
}
3. 使用@ControllerAdvice配合@InitBinder
要對Spring MVC的控制器進(jìn)行全局的配置,可以使用@ControllerAdvice注解。然后,在這個類中使用@InitBinder注解的方法來注冊自定義的屬性編輯器。
注意:@InitBinder主要用于處理表單數(shù)據(jù)的綁定,對于JSON數(shù)據(jù)的序列化和反序列化,它并不是最直接的方法。但如果是處理非JSON格式的請求體(如表單數(shù)據(jù)),則可以使用此方法。
使用場景(對于JSON數(shù)據(jù),更偏向于使用其他方法;對于表單數(shù)據(jù)):
- 當(dāng)需要對表單數(shù)據(jù)的綁定進(jìn)行自定義處理時。
- 當(dāng)需要在多個控制器中復(fù)用相同的表單數(shù)據(jù)綁定邏輯時。
創(chuàng)建一個自定義的屬性編輯器:
public class CustomLocalDateTimeEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(LocalDateTime.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
}
@Override
public String getAsText() {
LocalDateTime value = (LocalDateTime) getValue();
return value.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
}
然后,在@ControllerAdvice類中注冊這個屬性編輯器:
@ControllerAdvice
public class CustomControllerAdvice {
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(LocalDateTime.class, new CustomLocalDateTimeEditor());
}
}
4. 自定義HttpMessageConverter
可以編寫自定義的HttpMessageConverter來處理特定的媒體類型,并在其中實現(xiàn)自定義的序列化和反序列化邏輯。然后,將其注冊到Spring MVC的配置中。
使用場景:
- 當(dāng)Spring Boot默認(rèn)的HttpMessageConverter無法滿足自定義的序列化和反序列化需求時。
- 當(dāng)需要處理非標(biāo)準(zhǔn)的媒體類型時,如自定義的二進(jìn)制格式或文本格式。
- 當(dāng)需要在序列化和反序列化過程中應(yīng)用復(fù)雜的業(yè)務(wù)邏輯時。
創(chuàng)建一個自定義的HttpMessageConverter:
public class CustomLocalDateTimeConverter extends MappingJackson2HttpMessageConverter {
public CustomLocalDateTimeConverter() {
super();
ObjectMapper customObjectMapper = new ObjectMapper();
customObjectMapper.registerModule(new CustomJacksonModule());
setObjectMapper(customObjectMapper);
}
}
然后,在配置類中注冊這個轉(zhuǎn)換器:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(0, new CustomLocalDateTimeConverter());
}
}
5. 使用AOP進(jìn)行切面編程
可以使用Spring AOP來對控制器的方法進(jìn)行切面,從而在方法執(zhí)行前后進(jìn)行自定義的序列化和反序列化操作。
使用場景:
- 當(dāng)需要在不修改原有業(yè)務(wù)代碼的情況下,對方法入?yún)⒑统鰠⑦M(jìn)行額外的處理時。
- 當(dāng)需要對多個控制器或方法中的入?yún)⒑统鰠?yīng)用統(tǒng)一的處理邏輯時。
- 當(dāng)處理邏輯與業(yè)務(wù)邏輯相對獨立,且需要保持代碼結(jié)構(gòu)清晰時。
首先,定義一個切面:
@Aspect
@Component
public class CustomSerializationAspect {
@Before("execution(* com.example.controller..*.*(..)) && args(..,@RequestParam(..),@RequestBody(..))")
public void beforeControllerMethod(JoinPoint joinPoint) {
// 在這里可以修改入?yún)?,但通常不建議這么做,因為這會改變方法的簽名
// 更常見的是在處理響應(yīng)后進(jìn)行修改
}
@AfterReturning(pointcut = "execution(* com.example.controller..*.*(..)) && @annotation(org.springframework.web.bind.annotation.RequestMapping)", returning = "result")
public void afterControllerMethod(JoinPoint joinPoint, Object result) {
// 在這里可以修改出參,例如將LocalDateTime轉(zhuǎn)換為特定格式的字符串
if (result instanceof MyEntity) {
MyEntity entity = (MyEntity) result;
// 假設(shè)你想在這里修改entity的dateTime字段
}
}
}
注意:AOP通常用于橫切關(guān)注點的處理,如日志、事務(wù)管理等,而不是用于修改方法的入?yún)⒑统鰠?。如果你需要修改入?yún)⒑统鰠?,通常建議使用其他方法,如自定義的HttpMessageConverter或@ControllerAdvice。在上面的AOP示例中看到了如何捕獲方法的執(zhí)行,但實際上修改入?yún)⑹遣煌扑]的,而出參的修改也通常不是AOP的最佳用途。如果確實需要在AOP中修改出參,你可能需要考慮使用@AfterReturning注解,并檢查返回值的類型,然后進(jìn)行相應(yīng)的處理。然而,更常見做法是使用Jackson的序列化特性或@ControllerAdvice來全局處理響應(yīng)體的格式。
結(jié)語
Spring Boot, Spring Cloud 中要增強請求出入?yún)⒌姆绞街? 通常,對于簡單的自定義需求,使用@JsonSerialize和@JsonDeserialize注解是最直接和簡單的方式。而對于更復(fù)雜的全局配置或跨多個控制器的需求,則可能需要使用ObjectMapper的配置或@ControllerAdvice。
以上就是SpringBoot接口請求入?yún)⒑统鰠⒃鰪姷奈宸N方法的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot接口出入?yún)⒃鰪姷馁Y料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
詳解IDEA2020新建spring項目和c3p0連接池的創(chuàng)建和使用
C3P0是一個開源的JDBC連接池,它實現(xiàn)了數(shù)據(jù)源和JNDI綁定,本文就使用Spring實現(xiàn),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08
java實現(xiàn)word轉(zhuǎn)pdf or直接生成pdf文件
這篇文章主要介紹了java實現(xiàn)word轉(zhuǎn)pdf or直接生成pdf文件方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-04-04
SpringBoot實現(xiàn)文章防盜鏈的代碼設(shè)計
這篇文章主要介紹了SpringBoot實現(xiàn)文章防盜鏈的代碼設(shè)計,文中通過代碼示例講解的非常詳細(xì),對大家實現(xiàn)文章防盜鏈功能有一定的幫助,需要的朋友可以參考下2024-05-05
Java 使用keytool創(chuàng)建CA證書的操作
這篇文章主要介紹了Java 使用keytool創(chuàng)建CA證書的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01

