@Configuration//表明这是一个配置类
public class WebConfig implements WebMvcConfigurer
{
//自定义Stirng--->Pet的类型转换器
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new Converter<String,Pet>() {
@Override
public Pet convert(String source)//这里的source就是对应要String--->Pet的string字符串
{
// 啊猫,3
if(!StringUtils.isEmpty(source)){
Pet pet = new Pet();
String[] split = source.split(",");
pet.setName(split[0]);
pet.setAge(Integer.parseInt(split[1]));
return pet;
}
return null;
}
});
}
};
测试:
@RestController
public class myController
{
@GetMapping("/hello")
//通过路径变量,占位符进行相同名字的区分
public Map boss(Pet pet)
{
Map<String,Object> map = new HashMap<>();
map.put("pet",pet);
return map;
}
}