import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.validation.DataBinder;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class DataBinderTest {
public static void main(String[] args) {
{
// 要填充的目标对象 & 绑定器
FooOneEntity bindObject0 = new FooOneEntity();
String bindObject0Name = "bindObject0Name";
DataBinder dataBinder = new DataBinder(bindObject0, bindObject0Name);
// 数据源
Map mapData = new HashMap<>();
mapData.put("fooName", "fooName_val");
MutablePropertyValues mpvs = new MutablePropertyValues(mapData);
// 绑定数据到目标对象
dataBinder.bind(mpvs);
log.info("bindObject0 = {}", bindObject0);
log.info("binder.getBindingResult() = {}", dataBinder.getBindingResult());
log.info("binder.getBindingResult().getModel() = {}", dataBinder.getBindingResult().getModel());
}
{
String cookieName = "cookieName";
Object cookieValue = "cookieName_val"; // 参数值
Class paramType = String.class; // 参数类型
// 绑定器
DataBinder dataBinder = new DataBinder(null, cookieName);
// 转换数据
Object object = dataBinder.convertIfNecessary(cookieValue, paramType);
log.info("object = {}", object);
}
}
@Data
static class FooOneEntity {
private Integer id;
private String fooName;
}
}
结果
11:27:14.248 [main] INFO cn.java.demo.base.webmvc.internal.DataBinderTest - bindObject0 = DataBinderTest.FooOneEntity(id=null, fooName=fooName_val)
11:27:14.253 [main] INFO cn.java.demo.base.webmvc.internal.DataBinderTest - binder.getBindingResult() = org.springframework.validation.BeanPropertyBindingResult: 0 errors
11:27:14.253 [main] INFO cn.java.demo.base.webmvc.internal.DataBinderTest - binder.getBindingResult().getModel() = {bindObject0Name=DataBinderTest.FooOneEntity(id=null, fooName=fooName_val), org.springframework.validation.BindingResult.bindObject0Name=org.springframework.validation.BeanPropertyBindingResult: 0 errors}
11:27:14.254 [main] INFO cn.java.demo.base.webmvc.internal.DataBinderTest - object = cookieName_val