Spring对象绑定与类型转换

Spring对象绑定与类型转换

Spring的框架体系中,到处充斥着对象绑定从bean的初始化autowired属性,SpringMvc 中对对象的绑定等。Spring对象绑定和类型转换在Spring体系中发挥着至关重要的作用。其对象绑定是通过属性编辑器体现来完成,类型转换是通过Spring 3.0以后引入的全新框架。属性编辑器也能实现部分类型转换的功能,但主要是对象类型跟String类型之间的转换。全新而类型转换框架ConversionService则是实现任意类型之间的转换,一个更通用更灵活的框架。

1. 属性编辑器:

public class TestWrapper {
    private TestBean testBean;

    public void setTestBean(TestBean testBean) {
        this.testBean = testBean;
    }

    public TestBean getTestBean() {
        return testBean;
    }
}
public class TestBeanEditor extends PropertyEditorSupport{
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        TestBean testBean = new TestBean();
        StringTokenizer st = new StringTokenizer(text,"-");
        testBean.setName(st.nextToken());
        testBean.setPassword(st.nextToken());
        testBean.setAge(Integer.parseInt(st.nextToken()));
        setValue(testBean);
    }
}
TestWrapper testBean = new TestWrapper();
BeanWrapper beanWrapper = new BeanWrapperImpl(testBean);
beanWrapper.registerCustomEditor(TestBean.class,new TestBeanEditor());
beanWrapper.setPropertyValue("testBean","aa-bb-12");
System.out.println(testBean.getTestBean().toString());

2. 类型转换器:

我们经常会遇到的一种场景,根据ID查找实体对象,通常从前端传入实体的ID,后台接收到ID后,我们接收参数,然后查询数据库获取实体对象。在这类型转换器也能轻松办到。

public class User {
    private String name;
    private String password;

    public String getName() {
        return name;
    }

    public String getPassword() {
        return password;
    }

    public User(String name, String password){
        this.name = name;
        this.password = password;
    }

    public static User findUser(String name){
        return UserPools.findByUsername(name);
    }
}

注意,findUser是关键方法,且必须为静态方法。不需要对象便可调用,参数必须为ID。

@RequestMapping("/user")
public User getUser(@RequestParam("user") User user){
  return user;
}
mockMvc.perform(MockMvcRequestBuilders.post("/user")
    .contentType(MediaType.APPLICATION_JSON_UTF8).param("user","zhangsan")).andExpect(
    MockMvcResultMatchers.content().json(JSON.toJSONString(UserPools.findByUsername("zhangsan")))
);

当然,Spring内置了大量常用的类型转换器,本文不详细阐述。

posted @ 2016-12-31 17:40  dragonfei  阅读(945)  评论(0编辑  收藏  举报