使用场景
1 数据绑定
2 BeanWrapper
3 Spring拓展PropertyEditor
案例演示:
public class StringToPropertiesPropertyEditor extends PropertyEditorSupport implements PropertyEditor {
// 1.实现setAsTest() 方法
@Override
public void setAsText(String text) throws IllegalArgumentException {
Properties properties = new Properties();
try {
properties.load(new StringReader(text));
} catch (IOException e) {
throw new RuntimeException(e);
}
setValue(properties);
}
}
public class ConversionDemo {
public static void main(String[] args) {
String text = "name = 李勇";
PropertyEditor propertyEditor = new StringToPropertiesPropertyEditor();
propertyEditor.setAsText(text);
System.out.println(propertyEditor.getValue());
}
}
4 Spring内建实现
5 自定义PropertyEditor拓展
public class CustomizePropertyEditorRegistrar implements PropertyEditorRegistrar {
@Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Person.class, "context", new StringToPropertiesPropertyEditor());
}
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(CustomizePropertyEditorRegistarDemo.class);
context.refresh();
Person person = context.getBean("person", Person.class);
System.out.println(person);
context.close();
}
@Value("name=liyong")
private Properties context;
我们会发现,我们写的值会被转换为Properties对象。
6 PropertyEditor 设计缺陷
Spring3 通用类型转换
内建实现:
Converter接口的局限性:
自定义拓展:
public class PropertiesToStringConverter implements ConditionalGenericConverter {
@Override
public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
return Properties.class.equals(sourceType.getObjectType())
&& String.class.equals(targetType.getObjectType());
}
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(Properties.class, String.class));
}
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
Properties properties = (Properties) source;
StringBuilder builder = new StringBuilder();
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
builder.append(entry.getKey()).append("=").append(entry.getValue())
.append(System.getProperty("line.separator"));
}
return builder;
}
}
这里进行注册时候后名称必须为conversionService