在我的Spring / Boot Java项目中,我有一组服务方法,例如下面的一个:
@Override
public Decision create(String name, String description, String url, String imageUrl, Decision parentDecision, Tenant tenant, User user) {
name = StringUtils.trimMultipleSpaces(name);
if (org.apache.commons.lang3.StringUtils.isEmpty(name)) {
throw new IllegalArgumentException("Decision name can't be blank");
}
if (!org.apache.commons.lang3.StringUtils.isEmpty(url) && !urlValidator.isValid(url)) {
throw new IllegalArgumentException("Decision url is not valid");
}
if (!org.apache.commons.lang3.StringUtils.isEmpty(imageUrl) && !urlValidator.isValid(imageUrl)) {
throw new IllegalArgumentException("Decision imageUrl is not valid");
}
if (user == null) {
throw new IllegalArgumentException("User can't be empty");
}
if (tenant != null) {
List<Tenant> userTenants = tenantDao.findTenantsForUser(user.getId());
if (!userTenants.contains(tenant)) {
throw new IllegalArgumentException("User doesn't belong to this tenant");
}
}
if (parentDecision != null) {
if (tenant == null) {
if (findFreeChildDecisionByName(parentDecision.getId(), name) != null) {
throw new EntityAlreadyExistsException("Parent decision already contains a child decision with a given name");
}
} else {
if (findTenantedChildDecisionByName(parentDecision.getId(), name, tenant.getId()) != null) {
throw new EntityAlreadyExistsException("Parent decision already contains a child decision with a given name");
}
}
Tenant parentDecisionTenant = tenantDao.findTenantForDecision(parentDecision.getId());
if (parentDecisionTenant != null) {
if (tenant == null) {
throw new IllegalArgumentException("Public decision cannot be added as a child to tenanted parent decision");
}
if (!parentDecisionTenant.equals(tenant)) {
throw new IllegalArgumentException("Decision cannot belong to tenant other than parent decision tenant");
}
} else {
if (tenant != null) {
throw new IllegalArgumentException("Tenanted decision cannot be added as a child to public parent decision");
}
}
} else {
if (tenant == null) {
if (findFreeRootDecisionByName(name) != null) {
throw new EntityAlreadyExistsException("Root decision with a given name already exists");
}
} else {
if (findTenantedRootDecisionByName(name, tenant.getId()) != null) {
throw new EntityAlreadyExistsException("Root decision with a given name for this tenant already exists");
}
}
}
Decision decision = createOrUpdate(new Decision(name, description, url, imageUrl, parentDecision, user, tenant));
if (parentDecision != null) {
parentDecision.addChildDecision(decision);
}
criterionGroupDao.create(CriterionGroupDaoImpl.DEFAULT_CRITERION_GROUP_NAME, null, decision, user);
characteristicGroupDao.create(CharacteristicGroupDaoImpl.DEFAULT_CHARACTERISTIC_GROUP_NAME, null, decision, user);
return decision;
}
正如您所看到的,此方法的大多数代码行都被验证逻辑占用,我继续在那里添加新的验证案例。
我想重构此方法,并在更合适的位置移动此方法之外的验证逻辑。请建议如何使用Spring框架完成。
答案 0 :(得分:2)
正如chrylis在评论中提到的,您可以通过使用JSR-303 bean验证来实现此目标。第一步是创建一个包含输入参数的类:
public class DecisionInput {
private String name;
private String description;
private String url;
private String imageUrl;
private Decision parentDecision;
private Tenant tenant;
private User user;
// Constructors, getters, setters, ...
}
之后,您可以开始添加验证注释,例如:
public class DecisionInput {
@NotEmpty
private String name;
@NotEmpty
private String description;
@NotEmpty
private String url;
@NotEmpty
private String imageUrl;
private Decision parentDecision;
private Tenant tenant;
@NotNull
private User user;
// Constructors, getters, setters, ...
}
请注意@NotEmpty
注释不是标准的JSR-303注释,而是Hibernate注释。如果您更喜欢使用标准JSR-303,您始终可以创建自己的自定义验证器。对于您的租户和您的决定,您当然需要一个自定义验证器。首先创建一个注释(例如@ValidTenant
)。在注释类中,请确保添加@Constraint
注释,例如:
@Constraint(validatedBy = TenantValidator.class) // Your validator class
@Target({ TYPE, ANNOTATION_TYPE }) // Static import from ElementType, change this to METHOD/FIELD if you want to create a validator for a single field (rather than a cross-field validation)
@Retention(RUNTIME) // Static import from RetentionPolicy
@Documented
public @interface ValidTenant {
String message() default "{ValidTenant.message}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
现在您必须创建TenantValidator
类并使其实现ConstraintValidator<ValidTenant, DecisionInput>
,例如:
@Component
public class TenantValidator implements ConstraintValidator<ValidTenant, DecisionInput> {
@Autowired
private TenantDAO tenantDao;
@Override
public void initialize(ValidTenant annotation) {
}
@Override
public boolean isValid(DecisionInput input, ConstraintValidatorContext context) {
List<Tenant> userTenants = tenantDao.findTenantsForUser(input.getUser().getId());
return userTenants.contains(input.getTenant());
}
}
对父母决定的验证也可以这样做。现在您可以将服务方法重构为:
public Decision create(@Valid DecisionInput input) {
// No more validation logic necessary
}
如果您想使用自己的错误消息,建议您阅读this answer。基本上,您创建了一个ValidationMessages.properties
文件并将消息放在那里。