这篇文章主要讲解了“Spring中的类型转换器怎么定义使用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“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());
    
}打印结果: