跳到主要内容

吃透Spring源码(四):自定义属性编辑器PropertyEditor

> Spring的强大之处不仅仅在于它为Java开发者提供了极大便利,更在于它的开放式架构,使得用户可以拥有最大扩展Spring的能力。

我们在xml定义bean时,输入的内容都是字符串。spring会根据已经注册好的属性编辑器解析这些字符串,实例化成对应的类型。

一,源码相关

1,创建默认的propertyEditorRegister

 

在AbstractApplicationContext的refresh()方法的prepareBeanFactory()方法中创建一个默认的PropertyEditorRegister放入beanFactory中,此类主要负责注入如下默认的属性编辑器:

public void registerCustomEditors(PropertyEditorRegistry registry) {


ResourceEditor baseEditor = new ResourceEditor(this.resourceLoader, this.propertyResolver);
doRegisterEditor(registry, Resource.class, baseEditor);
doRegisterEditor(registry, ContextResource.class, baseEditor);
doRegisterEditor(registry, InputStream.class, new InputStreamEditor(baseEditor));
doRegisterEditor(registry, InputSource.class, new InputSourceEditor(baseEditor));
doRegisterEditor(registry, File.class, new FileEditor(baseEditor));
doRegisterEditor(registry, Path.class, new PathEditor(baseEditor));
doRegisterEditor(registry, Reader.class, new ReaderEditor(baseEditor));
doRegisterEditor(registry, URL.class, new URLEditor(baseEditor));

ClassLoader classLoader = this.resourceLoader.getClassLoader();
doRegisterEditor(registry, URI.class, new URIEditor(classLoader));
doRegisterEditor(registry, Class.class, new ClassEditor(classLoader));
doRegisterEditor(registry, Class[].class, new ClassArrayEditor(classLoader));

if (this.resourceLoader instanceof ResourcePatternResolver) {


doRegisterEditor(registry, Resource[].class,
new ResourceArrayPropertyEditor((ResourcePatternResolver) this.resourceLoader, this.propertyResolver));
}
}