這里面我們簡單的學習一下springboot中關於類型轉換器的使用。人世間的事情莫過於此,用一個瞬間來喜歡一樣東西,然后用多年的時間來慢慢拷問自己為什么會喜歡這樣東西。
springboot中的類型轉換器
我們的測試環境是springboot,一個將字符串轉換成對象的例子。代碼結構如下:
一、實體的java類Person
package com.linux.huhx.learn.converter; import java.io.Serializable; /** * @Author: huhx * @Date: 2017-12-15 下午 3:30 * @Desc: 實體類 */ public class Person implements Serializable { private String username; private String password; private int age; public Person(String username, String password, int age) { this.username = username; this.password = password; this.age = age; } // ...get set方法 }
二、定義我們的將字符串轉換成Person對象的轉換器
這里需要用@Component注解標識,以便被springboot納入管理。
package com.linux.huhx.learn.converter; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; /** * @Author: huhx * @Date: 2017-12-15 下午 3:31 * @Desc: 這里面的功能比較弱,主要是為了學習converter,代碼不是特別的嚴謹。 */ @Component public class PersonConverter implements Converter<String, Person> { @Override public Person convert(String source) { if (StringUtils.isEmpty(source)) { return null; } System.out.println("input string: " + source); String[] inputParams = source.split("-"); Person person = new Person(inputParams[0], inputParams[1], Integer.valueOf(inputParams[2])); return person; } }
三、我們的測試控制器類
package com.linux.huhx.learn.converter; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @Author: huhx * @Date: 2017-12-15 下午 3:46 * @Desc: 測試springboot中自定義類型轉換器 */ @RestController @RequestMapping("/converter") public class PersonConverterAction { @PostMapping("/person") public Person convertrStringToPerson(Person person) { return person; } }
通過postman發送post的請求:url為localhost:9998/converter/person。下面的截圖是請求的數據,注意這里面的key=person與上述的convertrStringToPerson方法的參數名對應。
返回數據:
{ "username": "linux", "password": "123456", "age": 345 }
控制台打印請求的參數:
input string: linux-123456-345
友情鏈接
- 一個比較好的converter和formatter的學習博客:https://segmentfault.com/a/1190000005708254