De hecho, BeanUtils ConvertUtils dependientes para completar la conversión de tipo real, pero a veces es posible que necesite personalizar el convertidor para completar el elenco con necesidades especiales;
convertidor de tipo personalizado etapas de:
1, la definición de una clase que implementa una interfaz implementada convertidor
2, llamar al método ConvertUtils.register, registrar el convertidor
como un ejemplo, cuando la conversión de series, más un prefijo
package com.wyy.controller;
import com.wyy.pojo.User;
import com.wyy.utils.MyStringConverter;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
/**
* @author yuanyuan.wang
* @date 2019/12/18
*/
@Controller
public class StringConverter {
@GetMapping("/stringConverter")
@ResponseBody
public String DoStringConverter() throws InvocationTargetException, IllegalAccessException {
ConvertUtils.register(new MyStringConverter(),String.class);
Map<String,String> map = new HashMap<>();
map.put("id","001");
map.put("username","as");
map.put("password","as");
User user = new User();
BeanUtils.populate(user,map);
return "stringConverter";
}
}
package com.wyy.utils;
import org.apache.commons.beanutils.Converter;
/**
* @author yuanyuan.wang
* @date 2019/12/18
*/
public class MyStringConverter implements Converter {
@Override
public Object convert(Class aClass, Object o) {
if(String.class.isInstance(o)) {
return "##"+o;
}else {
return o;
}
}
}
Hay que destacar aquí, como BeanUtils, ConvertUtils y herramientas PropertyUtils están compartiendo el mismo convertidor, aunque esta forma es fácil de usar, pero a veces no parece lo suficientemente flexible, de hecho, BeanUtils ConvertUtils y tiene un correspondiente PropertyUtils clase puede ser instanciado, es decir BeanUtilsBean, ConvertUtilsBean, PropertyUtilsBean;
Su función y BeanUtils, ConvertUtils y PropertyUtils similar, excepto que se pueden crear instancias y cada instancia puede tener su propio convertidor de tipos
Fecha de Ingreso del convertidor
Referencia vínculos de documento: http://blog.sina.com.cn/s/blog_3eb047df0100o5u2.html
package com.wyy.controller;
import com.wyy.pojo.Order;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author yuanyuan.wang
* @date 2019/12/18
*/
@Controller
public class DateConverter {
@GetMapping("/dateConverter")
@ResponseBody
public String DoDateConverter() throws InvocationTargetException, IllegalAccessException {
Order bean = new Order();
//注册日期转换器
ConvertUtils.register(new Converter(){
@Override
public Object convert(Class type, Object value) {
if(value==null){
return null;
}
if(!(value instanceof String)){
throw new ConversionException("只支持字符串的转换");
}
String date = (String) value;
if(date.trim().equals("")){
return null;
}
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
return df.parse(date);
} catch (ParseException e) {
throw new ConversionException(e);
}
}
}, Date.class);
BeanUtils.setProperty(bean, "id", "001");
BeanUtils.setProperty(bean, "date", "1111-11-11"); //beanutils框架会自动对数据进行转换
System.out.println(bean.getDate()); //date.toString()
return "dateConverter";
}
}