Spring中的底層架構核心概念類型轉換器詳解
1.類型轉換器作用
類型的轉換賦值
2.自定義類型轉換器
把string字符串轉換成user對象
/** * @program ZJYSpringBoot1 * @description: 把string字符串轉換成user對象 * @author: zjy * @create: 2022/12/27 05:38 */ public class StringToUserPropertyEditor extends PropertyEditorSupport implements PropertyEditor { @Override public void setAsText(String text) throws java.lang.IllegalArgumentException{ User user = new User(); user.setName(text); this.setValue(user); } }
public static void main(String[] args) { StringToUserPropertyEditor propertyEditor = new StringToUserPropertyEditor(); propertyEditor.setAsText("aaaaa"); User user = (User) propertyEditor.getValue(); System.out.println(user.getName()); }
打印結果:
2.1.在spring中怎么用呢?
2.1.1 用法
我現在希望@Value中的值可以賦值到User的name上
@Component public class UserService { @Value("zjy") private User user; public void test(){ System.out.println(user.getName()); } }
還用2中的自定義類型轉換器 StringToUserPropertyEditor,spring啟動后,StringToUserPropertyEditor會被注冊到容器中。
public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); UserService userService = (UserService) context.getBean( "userService"); userService.test(); }
打印結果:
2.1.2 解析
當spring運行到這行代碼的時候會判斷:自己有沒有轉換器可以把@value中的值轉換成User?沒有的話會去找用戶有沒有自定義轉換器,在容器中可以找到自定義的轉換器后,用自定義的轉換器進行轉換。
3.ConditionalGenericConverter
ConditionalGenericConverter 類型轉換器,會更強大一些,可以判斷類的類型
public class StringToUserConverter implements ConditionalGenericConverter { public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { return sourceType.getType().equals(String.class) && targetType.getType().equals(User.class); } public Set<ConvertiblePair> getConvertibleTypes() { return Collections.singleton(new ConvertiblePair(String.class,User.class)); } public Object convert(Object source,TypeDescriptor sourceType, TypeDescriptor targetType) { User user = new User(); user.setName((String) source); return user; } }
調用:
public static void main(String[] args) { DefaultConversionService conversionService = new DefaultConversionService(); conversionService.addConverter(new StringToUserConverter()); User user = conversionService.convert("zjyyyyy",User.class); System.out.println(user.getName()); }
打印結果:
4.總結
到此這篇關于Spring中的底層架構核心概念類型轉換器詳解的文章就介紹到這了,更多相關Spring類型轉換器內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot整合WebSocket實現聊天室流程全解
WebSocket協議是基于TCP的一種新的網絡協議。本文將通過SpringBoot集成WebSocket實現簡易聊天室,對大家的學習或者工作具有一定的參考學習價值,感興趣的可以了解一下2023-01-01