javax.validation.Validation类的使用及代码示例

x33g5p2x  于2022-01-31 转载在 其他  
字(13.5k)|赞(0)|评价(0)|浏览(263)

本文整理了Java中javax.validation.Validation类的一些代码示例,展示了Validation类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Validation类的具体详情如下:
包路径:javax.validation.Validation
类名称:Validation

Validation介绍

[英]This class is the entry point for Bean Validation.

There are three ways to bootstrap it:

  • The easiest approach is to build the default ValidatorFactory.
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();

In this case, the default validation provider resolver will be used to locate available providers.

The chosen provider is defined as followed:

  • if the XML configuration defines a provider, this provider is used
    • if the XML configuration does not define a provider or if no XML configuration is present the first provider returned by the ValidationProviderResolver instance is used.
  • The second bootstrap approach allows to choose a custom ValidationProviderResolver. The chosen ValidationProvider is then determined in the same way as in the default bootstrapping case (see above).
Configuration configuration = Validation 
.byDefaultProvider() 
.providerResolver( new MyResolverStrategy() ) 
.configure(); 
ValidatorFactory factory = configuration.buildValidatorFactory();
  • The third approach allows you to specify explicitly and in a type safe fashion the expected provider.

Optionally you can choose a custom ValidationProviderResolver.

ACMEConfiguration configuration = Validation 
.byProvider(ACMEProvider.class) 
.providerResolver( new MyResolverStrategy() )  // optionally set the provider resolver 
.configure(); 
ValidatorFactory factory = configuration.buildValidatorFactory();

Note:

  • The ValidatorFactory object built by the bootstrap process should be cached and shared amongst Validator consumers.
  • This class is thread-safe.
    [中]这个类是Bean验证的入口点。
    有三种方法可以引导它:
    *最简单的方法是构建默认的验证器工厂
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();

在这种情况下,默认的验证提供程序解析程序将用于定位可用的提供程序。
所选提供商的定义如下:
*如果XML配置定义了一个提供程序,则使用该提供程序
*如果XML配置没有定义提供程序,或者没有XML配置,则使用ValidationProviderResolver实例返回的第一个提供程序。
*第二种引导方法允许选择自定义ValidationProviderResolver。然后,选择的ValidationProvider将以与默认引导情况相同的方式确定(见上文)

Configuration configuration = Validation 
.byDefaultProvider() 
.providerResolver( new MyResolverStrategy() ) 
.configure(); 
ValidatorFactory factory = configuration.buildValidatorFactory();

*第三种方法允许您以类型安全的方式显式指定预期的提供程序。
也可以选择自定义ValidationProviderResolver。

ACMEConfiguration configuration = Validation 
.byProvider(ACMEProvider.class) 
.providerResolver( new MyResolverStrategy() )  // optionally set the provider resolver 
.configure(); 
ValidatorFactory factory = configuration.buildValidatorFactory();

注:
*引导过程生成的ValidatorFactory对象应该被缓存,并在验证器使用者之间共享。
*这个类是线程安全的。

代码示例

代码示例来源:origin: cloudfoundry/uaa

@Override
@SuppressWarnings("unchecked")
public void afterPropertiesSet() throws Exception {
  Assert.state(yaml != null, "Yaml document should not be null");
  Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
  try {
    logger.trace("Yaml document is\n" + yaml);
    configuration = (T) (new Yaml(constructor)).load(yaml);
    Set<ConstraintViolation<T>> errors = validator.validate(configuration);
    if (!errors.isEmpty()) {
      logger.error("YAML configuration failed validation");
      for (ConstraintViolation<?> error : errors) {
        logger.error(error.getPropertyPath() + ": " + error.getMessage());
      }
      if (exceptionIfInvalid) {
        @SuppressWarnings("rawtypes")
        ConstraintViolationException summary = new ConstraintViolationException((Set) errors);
        throw summary;
      }
    }
  } catch (YAMLException e) {
    if (exceptionIfInvalid) {
      throw e;
    }
  }
}

代码示例来源:origin: spring-projects/spring-framework

Configuration<?> configuration;
if (this.providerClass != null) {
  ProviderSpecificBootstrap bootstrap = Validation.byProvider(this.providerClass);
  if (this.validationProviderResolver != null) {
    bootstrap = bootstrap.providerResolver(this.validationProviderResolver);
  configuration = bootstrap.configure();
  GenericBootstrap bootstrap = Validation.byDefaultProvider();
  if (this.validationProviderResolver != null) {
    bootstrap = bootstrap.providerResolver(this.validationProviderResolver);
  configuration = bootstrap.configure();
  targetInterpolator = configuration.getDefaultMessageInterpolator();
configuration.messageInterpolator(new LocaleContextMessageInterpolator(targetInterpolator));
  configuration.traversableResolver(this.traversableResolver);
this.validatorFactory = configuration.buildValidatorFactory();
setTargetValidator(this.validatorFactory.getValidator());

代码示例来源:origin: apache/incubator-dubbo

@SuppressWarnings({"unchecked", "rawtypes"})
public JValidator(URL url) {
  this.clazz = ReflectUtils.forName(url.getServiceInterface());
  String jvalidation = url.getParameter("jvalidation");
  ValidatorFactory factory;
  if (jvalidation != null && jvalidation.length() > 0) {
    factory = Validation.byProvider((Class) ReflectUtils.forName(jvalidation)).configure().buildValidatorFactory();
  } else {
    factory = Validation.buildDefaultValidatorFactory();
  }
  this.validator = factory.getValidator();
  this.methodClassMap = new ConcurrentHashMap<String, Class>();
}

代码示例来源:origin: signalapp/BitHub

private PushEvent getEventFromPayload(String payload) throws IOException {
 ObjectMapper     objectMapper = new ObjectMapper();
 PushEvent        event        = objectMapper.readValue(payload, PushEvent.class);
 ValidatorFactory factory      = Validation.buildDefaultValidatorFactory();
 Validator        validator    = factory.getValidator();
 validator.validate(event);
 return event;
}

代码示例来源:origin: spring-projects/spring-framework

@Override
public void afterPropertiesSet() {
  if (this.validator == null) {
    this.validator = Validation.buildDefaultValidatorFactory().getValidator();
  }
}

代码示例来源:origin: tst-labs/esocial

public static <T> Set<ConstraintViolation<T>> validar(T object, Class<?>... groups){
  Locale.setDefault(new Locale("pt", "BR"));
  ValidatorFactory factory = Validation.byDefaultProvider()
      .configure()
      .buildValidatorFactory();
  Validator validator = factory.getValidator();
  
  return validator.validate(object, groups);
}

代码示例来源:origin: ninjaframework/ninja

/**
 * Validate the given value.
 *
 * @param value   The value, may be null
 * @param field   The name of the field being validated, if applicable
 * @param context The Ninja request context
 */
@Override
public void validate(Object value, String field, Context context) {
  if (value != null) {
    final ValidatorFactory validatorFactory = javax.validation.Validation.buildDefaultValidatorFactory();
    final javax.validation.Validator validator = validatorFactory.getValidator();
    final Set<javax.validation.ConstraintViolation<Object>> violations = validator.validate(value);
    final Locale localeToUse = this.requestLanguage.getLocaleFromStringOrDefault(this.requestLanguage.getLanguage(context, Optional.<Result>empty()));
    final Validation validation = context.getValidation();
    for (final javax.validation.ConstraintViolation<Object> violation : violations) {
      final String violationMessage = validatorFactory.getMessageInterpolator().interpolate(
          violation.getMessageTemplate(),
          new NinjaContextMsgInterpolator(value, violation.getConstraintDescriptor()),
          localeToUse
      );
      final String messageKey = violation.getMessageTemplate().replaceAll("[{}]", "");
      final ConstraintViolation constraintViolation = new ConstraintViolation(
          messageKey, violation.getPropertyPath().toString(), violationMessage, violation.getInvalidValue());
      validation.addViolation(constraintViolation);
    }
  }
}

代码示例来源:origin: com.atlassian.plugins.rest/atlassian-rest-common

public ValidationInterceptor(MessageInterpolator messageInterpolator) {
  // Yes, this cast is unnecessary in Java 6, but seems to be required in Java 5
  this.factory = ((Configuration) Validation.byDefaultProvider().configure().messageInterpolator(messageInterpolator)).buildValidatorFactory();
}

代码示例来源:origin: linlinjava/litemall

@Bean
  public Validator validator() {
    ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
        .configure()
        .addProperty("hibernate.validator.fail_fast", "true")
        .buildValidatorFactory();
    Validator validator = validatorFactory.getValidator();

    return validator;
  }
}

代码示例来源:origin: org.jboss.ironjacamar/ironjacamar-core-impl

/**
* Constructor
*/
public BeanValidation()
{
 Configuration configuration = Validation.byDefaultProvider().configure();
 Configuration<?> conf = configuration.traversableResolver(new JCATraversableResolver());
 validatorFactory = conf.buildValidatorFactory();
 validator = validatorFactory.getValidator();
}

代码示例来源:origin: torakiki/sejda

private DefaultValidationContext() {
  Configuration<?> validationConfig = Validation.byDefaultProvider().configure();
  if (new DefaultSejdaContext().isIgnoreXmlConfiguration()) {
    validationConfig.ignoreXmlConfiguration();
  }
  ValidatorFactory factory = validationConfig.buildValidatorFactory();
  validator = factory.getValidator();
}

代码示例来源:origin: com.typesafe.play/play-java-forms

@Inject
public ValidatorProvider(ConstraintValidatorFactory constraintValidatorFactory, final ApplicationLifecycle lifecycle) {
  this.validatorFactory = Validation.byDefaultProvider().configure()
      .constraintValidatorFactory(constraintValidatorFactory)
      .messageInterpolator(new ParameterMessageInterpolator())
      .buildValidatorFactory();
  lifecycle.addStopHook(() -> {
    this.validatorFactory.close();
    return CompletableFuture.completedFuture(null);
  });
}

代码示例来源:origin: apache/servicecomb-java-chassis

@Override
public <T> void beforeMethodInvoke(SwaggerInvocation invocation, SwaggerProducerOperation producerOperation,
  Object[] args)
  throws ConstraintViolationException {
 if (null == executableValidator) {
  ValidatorFactory factory =
    Validation.byDefaultProvider()
      .configure()
      .parameterNameProvider(new DefaultParameterNameProvider())
      .buildValidatorFactory();
  executableValidator = factory.getValidator().forExecutables();
 }
 Set<ConstraintViolation<Object>> violations =
   executableValidator.validateParameters(producerOperation.getProducerInstance(),
     producerOperation.getProducerMethod(),
     args,
     Default.class);
 if (violations.size() > 0) {
  LOGGER.warn("Parameter validation failed : " + violations.toString());
  throw new ConstraintViolationException(violations);
 }
}

代码示例来源:origin: hibernate/hibernate-validator

public ValidationExtension() {
  Configuration<?> config = Validation.byDefaultProvider().configure();
  // we use the default ParameterNameProvider here as we cannot use the injected one
  // as it hasn't been turned into a managed bean yet and might not be able to
  // return a parameter name. At this stage, we don't care about the parameter names.
  config.parameterNameProvider( config.getDefaultParameterNameProvider() );
  BootstrapConfiguration bootstrap = config.getBootstrapConfiguration();
  globalExecutableTypes = bootstrap.getDefaultValidatedExecutableTypes();
  isExecutableValidationEnabled = bootstrap.isExecutableValidationEnabled();
  validatorFactory = config.buildValidatorFactory();
  validator = validatorFactory.getValidator();
  getterPropertySelectionStrategyHelper = GetterPropertySelectionStrategyHelper.forValidationFactory( validatorFactory );
  executableHelper = new ExecutableHelper( new TypeResolutionHelper() );
}

代码示例来源:origin: hibernate/hibernate-validator

public StatisticalValidationState() {
  ValidatorFactory factory = null;
  final Configuration<?> configuration = Validation.byDefaultProvider().configure();
  try ( InputStream mappingStream = StatisticalValidation.class.getResourceAsStream( "mapping.xml" ) ) {
    configuration.addMapping( mappingStream );
    factory = configuration.buildValidatorFactory();
    assertThat( factory ).isNotNull();
  }
  catch (IOException e) {
    throw new IllegalStateException( "Mappings cannot be read. Validation factory cannot be configured correctly.", e );
  }
  validator = factory.getValidator();
  entitiesUnderTest = IntStream.rangeClosed( 0, NUMBER_OF_TEST_ENTITIES )
      .mapToObj( index -> new TestEntity( index % 10 ) )
      .collect( Collectors.toList() );
}

代码示例来源:origin: javax.validation/validation-api

/**
 * Builds and returns a {@link ValidatorFactory} instance based on the
 * default Bean Validation provider and following the XML configuration.
 * <p>
 * The provider list is resolved using the default validation provider resolver
 * logic.
 * <p>
 * The code is semantically equivalent to
 * {@code Validation.byDefaultProvider().configure().buildValidatorFactory()}.
 *
 * @return {@code ValidatorFactory} instance
 *
 * @throws NoProviderFoundException if no Bean Validation provider was found
 * @throws ValidationException if a Bean Validation provider was found but the
 * {@code ValidatorFactory} cannot be built
 */
public static ValidatorFactory buildDefaultValidatorFactory() {
  return byDefaultProvider().configure().buildValidatorFactory();
}

代码示例来源:origin: spring-projects/spring-framework

@Override
public void afterPropertiesSet() {
  if (this.validatorFactory == null) {
    this.validatorFactory = Validation.buildDefaultValidatorFactory();
  }
  ValidatorContext validatorContext = this.validatorFactory.usingContext();
  MessageInterpolator targetInterpolator = this.messageInterpolator;
  if (targetInterpolator == null) {
    targetInterpolator = this.validatorFactory.getMessageInterpolator();
  }
  validatorContext.messageInterpolator(new LocaleContextMessageInterpolator(targetInterpolator));
  if (this.traversableResolver != null) {
    validatorContext.traversableResolver(this.traversableResolver);
  }
  setTargetValidator(validatorContext.getValidator());
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Create a new MethodValidationInterceptor using a default JSR-303 validator underneath.
 */
public MethodValidationInterceptor() {
  this(Validation.buildDefaultValidatorFactory());
}

代码示例来源:origin: wildfly/wildfly

private ValidatorFactory initFactory() {
  final ClassLoader oldTCCL = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
  try {
    WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader);
    return Validation.byDefaultProvider().providerResolver(new WildFlyProviderResolver()).configure()
        .buildValidatorFactory();
  } finally {
    WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTCCL);
  }
}

代码示例来源:origin: hibernate/hibernate-validator

private Configuration<?> getConfiguration() {
  return validationProviderHelper.isDefaultProvider() ?
      Validation.byDefaultProvider().configure() :
      Validation.byProvider( org.hibernate.validator.HibernateValidator.class ).configure();
}

相关文章