它的運作原理很簡單,Spring利用AOP攔截需要進行validation的method,在method執行的前、後進行驗證,如果有違反condition就拋出exception。
以下是一組設定範例:
Spring XML
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
<bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor" />
<bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor" />
Method Validation Sample
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.validation.annotation.Validated;
import com.gss.acl.service.ws.domain.AclUserDetails;
@Validated
public interface AclUserDetailsWebService {
@NotNull
AclUserDetails loadUserByUsername(@NotBlank String username);
}
這樣就能在interface中規範condition並強化domain service的完整性,而且將validation邏輯從implementation class中抽離。
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.validation.annotation.Validated;
import com.gss.acl.service.ws.domain.AclUserDetails;
@Validated
public interface AclUserDetailsWebService {
@NotNull
AclUserDetails loadUserByUsername(@NotBlank String username);
}