在 SpringBoot 中,当使用 URL 传参直接接收对象时,有时需要对特定属性进行类型转换,例如日期和自定义枚举类型。

日期类型转换

可以使用注解 @DateTimeFormat(pattern = 'yyyy-MM-dd') 对日期类型进行转换。

自定义枚举类型转换

对于自定义枚举类型,可以使用注解 @EnumConverter 对其进行转换。

常见问题排查

如果使用了上述注解但仍出现类型转换错误,可能需要检查依赖包是否正确引入。例如,使用 @DateTimeFormat 注解时,需要引入 org.springframework.format.annotation.DateTimeFormat 依赖包。

示例代码

import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Date;

@Entity
public class MyEntity {
    @Id
    private Long id;

    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date endTime;

    @Convert(converter = EnumConverter.class)
    private MyEnum myEnum;
}

总结

通过使用 @DateTimeFormat@EnumConverter 注解,可以方便地对 URL 传参中的日期和自定义枚举类型进行转换。在使用过程中,需要注意依赖包的引入,以确保代码正常运行。

SpringBoot URL 传参对象类型转换:日期、枚举注解解析

原文地址: https://www.cveoy.top/t/topic/oXpf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录