Spring中的底层架构核心概念类型转换器详解
目录
- 1.类型转换器作用
- 2.自定义类型转换器
- 2.1.在spring中怎么用呢?
- 2.1.1 用法
- 2.1.2 解析
- 3.ConditionalGenericConverter
- 4.总结
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类型转换器内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
赞 (0)
