在Spring Boot中自定義序列化的方法是實現org.springframework.core.serializer.Serializer
接口或org.springframework.core.serializer.SmartSerializer
接口。
Serializer
接口,需要實現serialize(Object object, OutputStream outputStream)
方法,該方法負責將對象序列化為字節數組并寫入輸出流。SmartSerializer
接口,除了實現serialize
方法外,還需要實現boolean canSerialize(Class<?> clazz, MediaType mediaType)
方法,該方法用于判斷是否可以對指定的類進行序列化。在自定義序列化方法后,可以通過在Spring Boot的配置類中使用@Bean
注解將自定義的序列化器注入到Spring容器中,并通過配置文件配置使用該序列化器。
例如,使用Jackson庫自定義JSON序列化的示例代碼如下:
import org.springframework.core.serializer.Serializer;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonJsonSerializer implements Serializer<Object> {
private final ObjectMapper objectMapper;
public JacksonJsonSerializer() {
this.objectMapper = new ObjectMapper();
}
@Override
public void serialize(Object object, OutputStream outputStream) throws IOException {
objectMapper.writeValue(outputStream, object);
}
}
然后,在Spring Boot的配置類中將該序列化器注入到Spring容器中:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
@Configuration
public class MyConfig {
@Bean
public JacksonJsonSerializer jacksonJsonSerializer() {
return new JacksonJsonSerializer();
}
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(JacksonJsonSerializer serializer) {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(serializer.objectMapper);
return converter;
}
}
最后,在配置文件中配置使用自定義的序列化器:
spring.http.converters.preferred-json-mapper=jacksonJsonSerializer