Spring中的底层架构核心概念类型转换器详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Spring中的底层架构核心概念类型转换器详解

青苔小榭   2022-12-27 我要评论

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.总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们