Spring Boot 2.0 配置屬性自定義轉(zhuǎn)換的方法
引言
當(dāng)我們通過@ConfigurationProperties注解實(shí)現(xiàn)配置 bean的時候,如果默認(rèn)的配置屬性轉(zhuǎn)換無法滿足我們的需求的時候,我們可以根據(jù)自己的需求通過以下擴(kuò)展方式對配置屬性進(jìn)行轉(zhuǎn)換
PropertyEditorSupport實(shí)現(xiàn)
下面的例子是把屬性中定義的字符串轉(zhuǎn)換成Movie,并且把name的值大寫
繼承PropertyEditorSupport并且實(shí)現(xiàn)PropertyEditorRegistrar接口
package com.paderlol.spring.practice.properties.editor; import com.paderlol.spring.practice.properties.pojo.Movie; import java.beans.PropertyEditorSupport; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.PropertyEditorRegistrar; import org.springframework.beans.PropertyEditorRegistry; /** * @author pader PropertyEditor 在不同的包下面 */ @Slf4j public class CustomMovieEditor extends PropertyEditorSupport implements PropertyEditorRegistrar { @Override public String getAsText() { Movie movie = (Movie) getValue(); return movie == null ? "" : movie.getName(); } @Override public void setAsText(String text) throws IllegalArgumentException { log.info("繼承[PropertyEditorSupport]類,轉(zhuǎn)換數(shù)據(jù)={}", text); String[] data = text.split("-"); Movie movie = Movie.builder().name(data[0] .toUpperCase()).seat(Integer.parseInt(data[1])) .build(); setValue(movie); } @Override public void registerCustomEditors(PropertyEditorRegistry registry) { registry.registerCustomEditor(Movie.class,this); } }
注冊自定義的PropertyEditor
@Bean public CustomEditorConfigurer customEditorConfigurer() { CustomEditorConfigurer customEditorConfigurer = new CustomEditorConfigurer(); // 有兩種注冊方式 這是第一種 customEditorConfigurer.setPropertyEditorRegistrars( new PropertyEditorRegistrar[]{ new CustomMovieEditor() }); // 第二 種 Map<Class<?>,Class<? extends PropertyEditor>> maps = new HashMap<>(); maps.put(Movie.class,CustomMovieEditor.class); return customEditorConfigurer; }
Converter接口+@ConfigurationPropertiesBinding注解
//注意 @Component @ConfigurationPropertiesBinding public class StringToPersonConverter implements Converter<String, Person> { @Override public Person convert(String from) { log.info("使用[Converter]接口,轉(zhuǎn)換數(shù)據(jù)={}", from); String[] data = from.split(","); return Person.builder().name(data[0]).age(Integer.parseInt(data[1])).build(); } }
總結(jié)
- 以上兩種實(shí)現(xiàn)方式結(jié)果,但是Converter接口相比PropertyEditor接口更加靈活一些,PropertyEditor接口僅限于String轉(zhuǎn)換,Converter可以自定義別的,并且PropertyEditor接口通常用于Controller中的接收參數(shù)的轉(zhuǎn)換。
- @ConfigurationPropertiesBinding是限定符注解@Qualifier的派生類而已,參考o(jì)rg.springframework.boot.context.properties.ConversionServiceDeducer,以下是源代碼片段
@Autowired(required = false) @ConfigurationPropertiesBinding public void setConverters(List<Converter<?, ?>> converters) { this.converters = converters; } /** * A list of custom converters (in addition to the defaults) to use when * converting properties for binding. * @param converters the converters to set */ @Autowired(required = false) @ConfigurationPropertiesBinding public void setGenericConverters(List<GenericConverter> converters) { this.genericConverters = converters; }
- Formatter接口是不能對屬性完成轉(zhuǎn)換的,因為ConversionServiceDeducer初始化的時候只獲取GenericConverter和Converter接口
- 官方文檔上還介紹了可以使用實(shí)現(xiàn)org.springframework.core.convert.ConversionService并且Bean名稱也必須叫conversionService,不過大部分情況不推薦自己通過這種方式去實(shí)現(xiàn)這個接口,因為自己實(shí)現(xiàn)的ConversionService會替代默認(rèn)的。具體參考ConversionServiceDeducer源碼:
public ConversionService getConversionService() { try { //默認(rèn)首先尋找Bean名稱叫conversionService的ConversionService的Bean類 return this.applicationContext.getBean( ConfigurableApplicationContext.CONVERSION_SERVICE_BEAN_NAME, ConversionService.class); } catch (NoSuchBeanDefinitionException ex) { //找不到就默認(rèn)生成ApplicationConversionService類 return this.applicationContext.getAutowireCapableBeanFactory() .createBean(Factory.class).create(); } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Spring事件發(fā)布監(jiān)聽,順序監(jiān)聽,異步監(jiān)聽方式
這篇文章主要介紹了Spring事件發(fā)布監(jiān)聽,順序監(jiān)聽,異步監(jiān)聽方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12maven添加jar包到本地倉庫的實(shí)現(xiàn)
本文主要介紹了maven添加jar包到本地倉庫的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06詳解Java回調(diào)的原理與實(shí)現(xiàn)
回調(diào)函數(shù),顧名思義,用于回調(diào)的函數(shù)?;卣{(diào)函數(shù)只是一個功能片段,由用戶按照回調(diào)函數(shù)調(diào)用約定來實(shí)現(xiàn)的一個函數(shù)?;卣{(diào)函數(shù)是一個工作流的一部分,由工作流來決定函數(shù)的調(diào)用(回調(diào))時機(jī)。2017-03-03SpringBoot項目啟動時增加自定義Banner的簡單方法
最近看到springboot可以自定義啟動時的banner,然后自己試了一下,下面這篇文章主要給大家介紹了SpringBoot項目啟動時增加自定義Banner的簡單方法,需要的朋友可以參考下2022-01-01