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 用法
我現(xiàn)在希望@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;
}
}調(diào)用:
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類型轉換器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java多線程編程之訪問共享對象和數(shù)據(jù)的方法
這篇文章主要介紹了Java多線程編程之訪問共享對象和數(shù)據(jù)的方法,多個線程訪問共享對象和數(shù)據(jù)的方式有兩種情況,本文分別給出代碼實例,需要的朋友可以參考下2015-05-05
SpringBoot整合WebSocket實現(xiàn)聊天室流程全解
WebSocket協(xié)議是基于TCP的一種新的網(wǎng)絡協(xié)議。本文將通過SpringBoot集成WebSocket實現(xiàn)簡易聊天室,對大家的學習或者工作具有一定的參考學習價值,感興趣的可以了解一下2023-01-01
SpringBoot項目中出現(xiàn)不同端口跨域問題的解決方法
這篇文章主要介紹了SpringBoot項目中出現(xiàn)不同端口跨域問題的解決方法,文中介紹了兩種解決方法,并給出了詳細的代碼供大家參考,具有一定的參考價值,需要的朋友可以參考下2024-03-03
Java?20在Windows11系統(tǒng)下的簡易安裝教程
這篇文章主要給大家介紹了關于Java?20在Windows11系統(tǒng)下的簡易安裝教程,學習Java的同學,第一步就是安裝好Java環(huán)境,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2023-07-07

