Spring核心编程思想(九)重新认识 IoC之IoC 容器的实现

小马哥课程笔记

传统 IoC 容器的实现

Java Beans 作为 IoC 容器

JavaBeansDemo 元信息相关的不完整demo
PropertyDescriptor

在这里插入图片描述

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.util.stream.Stream;

/**
 * {@link BeanInfo} 示例
 *
 */
public class BeanInfoDemo {
    public static void main(String[] args) throws Exception{
        BeanInfo beanInfo = Introspector.getBeanInfo(Person.class);
        Stream.of(beanInfo.getPropertyDescriptors())
        .forEach(propertyDescriptor -> {
            System.out.println(propertyDescriptor);
        });

    }

}
输出

在这里插入图片描述

其中class属性就是在getBeanInfo要输入的stopClass
  • 来自于Object的本地方法getClass
  • 会被javaBeans当成一个属性
  • 因为通常来说访问对象是要通过方法而非直接访问字段,所以会被误认为一个Property
    在这里插入图片描述
此时只需要加上stopClass就可以防止出现这种问题
  • 为了解决如果一个类有多层次而目标只是当前层次的情况
  • 把父类写入到stopClass的位置
/**
 * {@link BeanInfo} 示例
 *
 */
public class BeanInfoDemo {
    public static void main(String[] args) throws Exception{
        BeanInfo beanInfo = Introspector.getBeanInfo(Person.class,Object.class);
        Stream.of(beanInfo.getPropertyDescriptors())
        .forEach(propertyDescriptor -> {
            System.out.println(propertyDescriptor);
        });
    }
}
类型配置和转换
public static void main(String[] args) throws Exception{
        BeanInfo beanInfo = Introspector.getBeanInfo(Person.class,Object.class);
        Stream.of(beanInfo.getPropertyDescriptors())
        .forEach(propertyDescriptor -> {
            // PropertyDescroptor 允许添加属性编辑器 - PropertyEditor
            // name -> String
            // age -> Integer
            Class<?> propertyType = propertyDescriptor.getPropertyType();
            String propertyName = propertyDescriptor.getName();
            if("age".equals(propertyName)){ // 为age 字段/属性 增加 PropertyEditor
                // String -> Integer   Integer.valueOf("1");
                propertyDescriptor.setPropertyEditorClass(StringToIntegerPropertyEditor.class);
                //propertyDescriptor.createPropertyEditor();
            }

        });

    }

    static class StringToIntegerPropertyEditor extends PropertyEditorSupport{
        public void setAsText(String text) throws java.lang.IllegalArgumentException {
            Integer value = Integer.valueOf(text);
            setValue(value);
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值