Spring 的类型转化

93 阅读1分钟

内部关系

beanFactory 包含 set<PropertyEditorRegistrar>.和一个ConversionService.

PropertyEditorRegistrar 的作用是给定一个PropertyEditorRegistry,能够对其进行添加PropertyEditor.

PropertyEditorRegistry 本身是一个 PropertyEditor 的存储中心,能够根据 class 注册或者获取一个PropertyEditor. 常见的实现了包括BeanWrapper,DataBinder等.

当需要BeanWarpper等类的时候,BeanFactory 可以用自己保存的set<PropertyEditorRegistrar> 对这些对象进行配置,传入PropertyEditor

BeanFactory 自己获取bean 进行类型转换的时候,是使用TypeConverter. 默认获取方法如下

public TypeConverter getTypeConverter() {
	TypeConverter customConverter = getCustomTypeConverter();
	if (customConverter != null) {
		return customConverter;
	}
	else {
		// Build default TypeConverter, registering custom editors.
		SimpleTypeConverter typeConverter = new SimpleTypeConverter();
		typeConverter.setConversionService(getConversionService());
		registerCustomEditors(typeConverter);
		return typeConverter;
	}
}

可以看到TypeConverter 使用PropertyEditor和ConversionService来实现.

applicationContext 如何配置ProppertyEditorConversationService

默认注册的

SimpleTypeConverter,BeanWrapperImpl默认都实现PropertyEditorRegistrySupport,而PropertyEditorRegistrySupport会创建默认的propertyEditor. 代码如下

//PropertyEditorRegistrySupport
private Map<Class<?>, PropertyEditor> defaultEditors;

public PropertyEditor getDefaultEditor(Class<?> requiredType);

createDefaultEditors();

fresh过程中的prepareBeanFactory 会执行 beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

CustomEditorConfigurer

改类是一个BeanFactoryPostProcessor,在所有的BeanDefinition实现后,会注入一些自定义的的PropertyEditor. 代码如下.

public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
	if (this.propertyEditorRegistrars != null) {
		for (PropertyEditorRegistrar propertyEditorRegistrar : this.propertyEditorRegistrars) {
			beanFactory.addPropertyEditorRegistrar(propertyEditorRegistrar);
		}
	}
	if (this.customEditors != null) {
		this.customEditors.forEach(beanFactory::registerCustomEditor);
	}
}

合适注册conversationService

spring 提供了ConversionServiceFactoryBean,这是一个FactoryBean,提供了很多默认的Converter.

applicatonContext 默认不注册 conversationService,但是在spring web环境和springboot环境下.应该会注册.