springboot笔记四:自定义Converter

通过springboot笔记三,我们已经学到自定义类型的参数是通过参数解析器ServletModelAttributeMethodProcessor创建WebDataBinder(web数据绑定器)进行参数封装,WebDataBinder属性ConversionService中有124个converters,我们也可以添加自定义Converter

通过WebMvcConfigurer 定制化springmvc的功能

package com.test.study.config;

import com.test.study.dto.Pet;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration(proxyBeanMethods = false)
public class Config implements WebMvcConfigurer {
    @Bean
    public WebMvcConfigurer webMvcConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void addFormatters(FormatterRegistry registry) {
                registry.addConverter(new Converter() {
                    @Override
                    public Pet convert(String str) {
                        if (!StringUtils.isEmpty(str)){
                            String[] split = str.split(",");
                            Pet pet = new Pet(split[0],Integer.valueOf(split[1]));
                            return pet;
                        }
                        return null;
                    }
                });
            }
        };
    }
}

controller接口

@RestController
@Slf4j
public class UserController {
    @PostMapping("/user/save")
    public UserDto save(UserDto userDto){
        return userDto;
    }
}

实体类

package com.test.study.dto;

import lombok.Data;

@Data
public class UserDto {
    private Long id;
    private String name;
    private String gender;
    private Integer age;

    private Pet pet;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Pet {
    private String name;
    private Integer age;
}

你可能感兴趣的:(spring学习,spring,boot,spring)