
本文旨在解决Spring应用中,如何针对不同类型的请求,实现灵活且可扩展的参数验证机制。通过结合抽象类和JSR-303注解,以及后置验证的方式,提供了一种优雅的解决方案,使得在新增请求类型时,无需修改现有代码,即可实现新的参数验证逻辑。
在实际的Spring Web开发中,我们经常会遇到需要根据不同的请求类型,进行不同参数验证的场景。例如,一个生成报告的接口,根据报告类型的不同,需要的参数也不同,对应的验证规则也随之变化。如果采用传统的单一DTO的方式,会导致验证逻辑复杂,难以维护,并且在新增报告类型时,需要修改大量的代码。本文将介绍一种使用抽象类和后置验证的方式,实现灵活可扩展的参数验证机制。
核心思路是定义一个抽象的请求参数DTO,包含所有请求共有的参数。然后,针对每种具体的请求类型,定义一个继承自抽象DTO的子类,包含该请求类型特有的参数。在Controller层,接收到请求后,根据请求类型,实例化对应的DTO子类,并进行验证。
首先,定义一个抽象类 ReportRequestDTO,包含所有报告类型共有的参数,并使用JSR-303注解进行验证。
import lombok.Data;
import javax.validation.constraints.NotEmpty;
@Data
public abstract class ReportRequestDTO {
@NotEmpty(message = "foo不能为空")
private String foo;
@NotEmpty(message = "bar不能为空")
private String bar;
}然后,针对每种报告类型,定义一个继承自 ReportRequestDTO 的子类,包含该报告类型特有的参数,并使用JSR-303注解进行验证。
import lombok.Data;
import javax.validation.constraints.NotEmpty;
@Data
public class ReportADTO extends ReportRequestDTO {
@NotEmpty(message = "foobar不能为空")
private String foobar;
}
@Data
public class ReportBDTO extends ReportRequestDTO {
@NotEmpty(message = "baz不能为空")
private String baz;
}在Controller层,接收到请求后,根据请求类型,实例化对应的DTO子类,并使用 javax.validation.Validator 进行验证。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validator;
import java.util.Optional;
import java.util.Set;
@RestController
public class ReportController {
@Autowired
private ReportFactory reportFactory;
@Autowired
private Validator validator;
@GetMapping("/report")
@ResponseBody
public ResponseEntity<String> getReport(
@RequestParam(value = "category") String category,
@Valid ReportRequestDTO reportRequestDTO) { // 注意这里使用抽象类,但实际上是需要手动创建对应的实现类
Optional<ReportCategory> reportCategory = ReportCategory.getReportCategoryByRequest(category);
if (reportCategory.isEmpty()) {
throw new IllegalArgumentException("Requested report category does not exist.");
}
ReportRequestDTO specificReportRequestDTO;
switch (reportCategory.get()) {
case REPORT_A:
specificReportRequestDTO = new ReportADTO();
// 将 reportRequestDTO 的公共属性复制到 specificReportRequestDTO
specificReportRequestDTO.setFoo(reportRequestDTO.getFoo());
specificReportRequestDTO.setBar(reportRequestDTO.getBar());
break;
case REPORT_B:
specificReportRequestDTO = new ReportBDTO();
// 将 reportRequestDTO 的公共属性复制到 specificReportRequestDTO
specificReportRequestDTO.setFoo(reportRequestDTO.getFoo());
specificReportRequestDTO.setBar(reportRequestDTO.getBar());
break;
default:
throw new IllegalArgumentException("Unsupported report category: " + category);
}
// 手动验证 specificReportRequestDTO
Set<ConstraintViolation<ReportRequestDTO>> violations = validator.validate(specificReportRequestDTO);
if (!violations.isEmpty()) {
// 处理验证失败的情况,例如抛出异常
StringBuilder errorMessage = new StringBuilder();
for (ConstraintViolation<ReportRequestDTO> violation : violations) {
errorMessage.append(violation.getMessage()).append("; ");
}
throw new IllegalArgumentException("Validation failed: " + errorMessage.toString());
}
try {
Report report = reportFactory.getReport(reportCategory.get());
return ResponseEntity.ok().body(report.generate(specificReportRequestDTO));
} catch (Exception e) {
throw new RuntimeException("Could not generate report.", e);
}
}
}
代码解释:
import org.springframework.stereotype.Component;
@Component
public class ReportFactory {
public Report getReport(ReportCategory category) {
switch (category) {
case REPORT_A:
return new ReportA();
case REPORT_B:
return new ReportB();
default:
throw new IllegalArgumentException("Unsupported report category: " + category);
}
}
}public abstract class Report {
public abstract String generate(ReportRequestDTO requestDTO);
}
import org.springframework.stereotype.Component;
@Component
public class ReportA extends Report {
@Override
public String generate(ReportRequestDTO requestDTO) {
ReportADTO reportADTO = (ReportADTO) requestDTO;
return "Report A generated with foo: " + reportADTO.getFoo() + ", bar: " + reportADTO.getBar() + ", foobar: " + reportADTO.getFoobar();
}
}
import org.springframework.stereotype.Component;
@Component
public class ReportB extends Report {
@Override
public String generate(ReportRequestDTO requestDTO) {
ReportBDTO reportBDTO = (ReportBDTO) requestDTO;
return "Report B generated with foo: " + reportBDTO.getFoo() + ", bar: " + reportBDTO.getBar() + ", baz: " + reportBDTO.getBaz();
}
}import java.util.Arrays;
import java.util.Optional;
public enum ReportCategory {
REPORT_A("reportA"),
REPORT_B("reportB");
private final String request;
ReportCategory(String request) {
this.request = request;
}
public String getRequest() {
return request;
}
public static Optional<ReportCategory> getReportCategoryByRequest(String request) {
return Arrays.stream(ReportCategory.values())
.filter(category -> category.request.equals(request))
.findFirst();
}
}本文介绍了一种使用抽象类和后置验证的方式,实现Spring应用中灵活可扩展的参数验证机制。通过定义抽象的请求参数DTO和具体的DTO子类,可以针对不同的请求类型,进行不同的参数验证。这种方式不仅代码结构清晰,易于维护,而且在新增请求类型时,无需修改现有代码,只需新增对应的DTO子类即可。
注意事项:
通过以上方式,可以实现一个可扩展、易于维护的参数验证机制,在新增报告类型时,只需要添加新的DTO类,并修改ReportFactory和ReportController即可,无需修改现有的代码,符合开闭原则。
以上就是Spring Validation:使用抽象请求参数类实现灵活的参数验证的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号