Spring的类型转换

1 类型转换说明

前台传参到后台,后台会对参数进行转换,封装成实体类中类型的参数.(常见: 时间字符串2021年4月12日21:56:50转换为Date类型时间)

时间类型转换应用

2 WebMvcConfigurer配置类

package org.springframework.web.servlet.config.annotation;

public interface WebMvcConfigurer {
    	/**
	 * Add {@link Converter Converters} and {@link Formatter Formatters} in addition to the ones
	 * registered by default.
	 */
	default void addFormatters(FormatterRegistry registry) {
	}

	/**
	 * Add Spring MVC lifecycle interceptors for pre- and post-processing of
	 * controller method invocations and resource handler requests.
	 * Interceptors can be registered to apply to all requests or be limited
	 * to a subset of URL patterns.
	 */
	default void addInterceptors(InterceptorRegistry registry) {
	}
    
    ...
}

/* 代码说明
FormatterRegistry实现了Spring自带的默认注册器,我们使用只需要加一个Converter和Formatter后,然后注册到FormatterRegistry中.
*/

3 Converter

/**
 * A converter converts a source object of type {@code S} to a target of type {@code T}.
 *
 * <p>Implementations of this interface are thread-safe and can be shared.
 *
 * <p>Implementations may additionally implement {@link ConditionalConverter}.
 *
 * @author Keith Donald
 * @author Josh Cummings
 * @since 3.0
 * @param <S> the source type
 * @param <T> the target type
 */
@FunctionalInterface
public interface Converter<S, T> {

	/**
	 * Convert the source object of type {@code S} to target type {@code T}.
	 * @param source the source object to convert, which must be an instance of {@code S} (never {@code null})
	 * @return the converted object, which must be an instance of {@code T} (potentially {@code null})
	 * @throws IllegalArgumentException if the source cannot be converted to the desired target type
	 */
	@Nullable
	T convert(S source);
    
    default <U> Converter<S, U> andThen(Converter<? super T, ? extends U> after) {
		Assert.notNull(after, "After Converter must not be null");
		return (S s) -> {
			T initialResult = convert(s);
			return (initialResult != null ? after.convert(initialResult) : null);
		};
	}
}
/* 代码说明:
	首先可以看到类上的@FunctionalInterface,说明支持函数式接口,支持Lambda变成.
	其次,接口的作用,就是将一个参数类型转换成另一个参数类型.Converter<S, T>中S代表源对象,T表示目标对象.
	再则,类上描述,实现此接口的类是线程安全的并且可被共享使用,安全的原因是它作用于方法体内,每次都用都是实例化一次,所以它是线程安全的.
*/

4 自定义转换案例

1自定义实现Converter接口


public class MyConverter implements Converter<String, Date> {
 
@Override    
	public Date convert(String source) {        
		Date date = null;        
		try {if(source.indexOf("-")>0){                
			date = new SimpleDateFormat("yyyy-MM-dd").parse(source);            
				}        
			} catch (ParseException e) {
			e.printStackTrace();        
			}        
		return date;    
	} 
}

2 自定义实现WebMvcConfigurer接口

/**
 * 添加参数转换器
 */
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
 
    /**
     *
     * @param registry
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new MyConverter());
    }
 
}

3 实体类

@Data
public class User {
 
    private String id;
 
    private Date birthday;
}

4 测试类

@RestController
@RequestMapping("/user")
public class UserController {
 
    @GetMapping("/queryUser")
    public void queryUser(User user) {
        // Xxx业务逻辑
        
        System.out.println("User = " + user);
    }
}

模拟请求:

http://localhost:8080/user/queryUser?id="001"&birthday="2021-04-12"

运行结果:

User(id=001, birthday=Mon Apr 12 00:00:00 CST 2021)
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值