首先,回顧一下在springMVC中如何實現類型轉換器,在springmvc中的類型轉換器,一般作用是將用戶提交的字符串類型的參數轉成其他自定義類型,springmvc已經提供很多常用的類型轉換器,例如:字符串轉換成日期,字符串轉換成Integer等。
第一步:添加自定義轉換器類:
public class EmployeeConverter implements Converter<string> {/<string>
@Override
public Employee convert(String s) {
if (s != null){
String[] strings = s.split("-");
if (strings != null && strings.length == 3){
Employee employee = new Employee();
employee.setId(strings[0]);
employee.setName(strings[1]);
employee.setSex(strings[2]);
return employee;
}
}
return null;
}
}
第二步:在springmvc配置中配置以讓轉換器生效
<annotation-driven>
<bean>
<property>
<list>
<bean>
那麼,在springboot中如何做呢?
由於springboot中有自動配置功能,自定義了類型轉換器不需要配置即可使用,代碼如下:
@Component // 加上註解,讓spring容器能管理並創建對象
public class EmployeeConverter implements Converter<string> {/<string>
@Override
public Employee convert(String s) {
if (s != null){
String[] strings = s.split("-");
if (strings != null && strings.length == 3){
Employee employee = new Employee();
employee.setId(strings[0]);
employee.setName(strings[1]);
employee.setSex(strings[2]);
return employee;
}
}
return null;
}
}
閱讀更多 瘋狂的亮亮 的文章