I am very new to Java and Spring Boot and trying to implement validation on the variable of a class as shown below and wants to validate each of the variables while initializing the value using the setter of the class.
import javax.validation.constraints.Digits;
import javax.validation.constraints.Size;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class LoanRequestBean {
@Size(max = 8)
String uniqueRefBancs;
@Digits(integer=2)
Integer loanId;
@Size(max = 20)
String loanIban;
}
The variable initialization is done by the setter as shown below.
import org.springframework.stereotype.Component;
@Component
public class BancsRequestRecords {
private String[] fieldsArray;
@Valid
LoanRequestBean loanRequest = new LoanRequestBean();
public loanRequestBean RequestParser(String message) {
fieldsArray = message.split("¬");
loanRequest.setUniqueRefBancs(fieldsArray[0]);
loanRequest.setLoanId(Integer.valueOf( fieldsArray[1]));
loanRequest.setLoanIban(fieldsArray[2]);
return loanRequest;
}
}
When I try to invoke Requestparser method with message as 2028110600000001000752¬123456¬FI9080706050403020 in the argument of the method, the values are not getting validated. eg: uniqueRefBancs has max length of 8 but still it does not throw any error while initialization. Could you please help me if it's the right approach to validate the variables or any any other way to achieve it?
CodePudding user response:
Bean Validation is performed when the @Valid or @Validated annotations are used on a method parameter. Further details here. You could use a method to validate your loanRequestBean. To check the result of validation you can use BindingResult. Edit: Unrelated but I would consider renmaing loanRequestBean to LoanRequestBean to follow java class name conventions.
CodePudding user response:
You would need to programmatically trigger the validation of your loanRequest object as follows:
import org.springframework.stereotype.Component;
@Component
public class BancsRequestRecords {
private LoanRequestBean loanRequest = new LoanRequestBean();
private Validator validator;
public BancsRequestRecords(Validator validator) {
this.validator = validator;
}
public loanRequestBean RequestParser(String message) {
String[] fieldsArray = message.split("¬");
loanRequest.setUniqueRefBancs(fieldsArray[0]);
loanRequest.setLoanId(Integer.valueOf( fieldsArray[1]));
loanRequest.setLoanIban(fieldsArray[2]);
Set<ConstraintViolation<LoanRequestBean>> violations = validator.validate(loanRequest);
return loanRequest;
}
}
You can read more about this at https://www.baeldung.com/javax-validation#programmatic.
