
本文旨在解决Spring应用中,如何针对不同类型的请求,实现灵活且可扩展的参数验证机制。通过结合抽象类和JSR-303注解,以及后置验证的方式,提供了一种优雅的解决方案,使得在新增请求类型时,无需修改现有代码,即可实现新的参数验证逻辑。
在实际的Spring Web开发中,我们经常会遇到需要根据不同的请求类型,进行不同参数验证的场景。例如,一个生成报告的接口,根据报告类型的不同,需要的参数也不同,对应的验证规则也随之变化。如果采用传统的单一DTO的方式,会导致验证逻辑复杂,难以维护,并且在新增报告类型时,需要修改大量的代码。本文将介绍一种使用抽象类和后置验证的方式,实现灵活可扩展的参数验证机制。
核心思路
核心思路是定义一个抽象的请求参数DTO,包含所有请求共有的参数。然后,针对每种具体的请求类型,定义一个继承自抽象DTO的子类,包含该请求类型特有的参数。在Controller层,接收到请求后,根据请求类型,实例化对应的DTO子类,并进行验证。
具体实现
1. 定义抽象请求参数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;
}2. 定义具体请求参数DTO
然后,针对每种报告类型,定义一个继承自 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;
}3. Controller层处理
在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 getReport(
@RequestParam(value = "category") String category,
@Valid ReportRequestDTO reportRequestDTO) { // 注意这里使用抽象类,但实际上是需要手动创建对应的实现类
Optional 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> violations = validator.validate(specificReportRequestDTO);
if (!violations.isEmpty()) {
// 处理验证失败的情况,例如抛出异常
StringBuilder errorMessage = new StringBuilder();
for (ConstraintViolation 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);
}
}
}
代码解释:
- @Autowired private Validator validator;: 注入JSR-303的Validator实例,用于手动验证DTO。
- ReportRequestDTO specificReportRequestDTO;:声明一个ReportRequestDTO类型的变量,用于存储根据category创建的具体DTO实例。
- switch (reportCategory.get()) { ... }:根据category的值,创建对应的DTO实例,例如ReportADTO或ReportBDTO。
- specificReportRequestDTO.setFoo(reportRequestDTO.getFoo());和specificReportRequestDTO.setBar(reportRequestDTO.getBar());:将通用的请求参数从reportRequestDTO复制到specificReportRequestDTO。
- Set
aintViolation > violations = validator.validate(specificReportRequestDTO);:使用validator.validate()方法手动验证specificReportRequestDTO实例。 - 如果验证失败,则遍历violations集合,构建错误信息,并抛出异常。
- 后续代码使用验证通过的specificReportRequestDTO实例生成报告。
4. ReportFactory
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);
}
}
}5. Report and its implementations
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();
}
}6. ReportCategory enum
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 getReportCategoryByRequest(String request) {
return Arrays.stream(ReportCategory.values())
.filter(category -> category.request.equals(request))
.findFirst();
}
} 总结
本文介绍了一种使用抽象类和后置验证的方式,实现Spring应用中灵活可扩展的参数验证机制。通过定义抽象的请求参数DTO和具体的DTO子类,可以针对不同的请求类型,进行不同的参数验证。这种方式不仅代码结构清晰,易于维护,而且在新增请求类型时,无需修改现有代码,只需新增对应的DTO子类即可。
注意事项:
- 在Controller层,需要手动实例化对应的DTO子类,并进行验证。
- 需要确保在Report的generate方法中,将ReportRequestDTO转换为对应的具体DTO类型。
- 这种方式适用于参数验证规则差异较大的场景。如果差异较小,可以考虑使用分组验证等其他方式。
通过以上方式,可以实现一个可扩展、易于维护的参数验证机制,在新增报告类型时,只需要添加新的DTO类,并修改ReportFactory和ReportController即可,无需修改现有的代码,符合开闭原则。








