How do I import javax.validation into my Java SE p

2019-02-01 22:38发布

2条回答
别忘想泡老子
2楼-- · 2019-02-01 23:06

Here are the dependencies I'm using (with Maven):

<dependencies>
  <!-- Bean Validation API and RI -->
  <dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.0.0.GA</version>
  </dependency>
  <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>4.0.2.GA</version>
  </dependency>
</dependencies>

That you can get from this repository:

<repositories>
  <repository>
    <id>jboss</id>
    <name>JBoss repository</name>
    <url>http://repository.jboss.org/maven2</url>
  </repository>
</repositories>
查看更多
啃猪蹄的小仙女
3楼-- · 2019-02-01 23:07

Latest dependencies:

    <!-- BeanValidation and Hibernate Validator. -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.4.0.Final</version>
    </dependency>        

This transitively pulls in the dependency to the Bean Validation API, so you don't need to do this anymore:

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
    </dependency>

For additional features, Expression Language and CDI support, you might need to add

    <dependency>
        <groupId>org.glassfish</groupId>
        <artifactId>javax.el</artifactId>
        <version>3.0.1-b08</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator-cdi</artifactId>
        <version>5.4.0.Final</version>
    </dependency>

Source: Hibernate Validator documentation

These all are both in Maven Central Repo, so you don't need to add the JBoss repo.

And BTW here's my example convenience method:

public static <T extends Object> void  validate( T object ) throws MigrationException
{
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<T>> valRes = validator.validate( object );
    if( ! valRes.isEmpty() )
    {
        StringBuilder sb = new StringBuilder("Validation failed for: ");
        if( object instanceof Origin.Wise )
            sb.append( ((Origin.Wise)object).getOrigin() );
        else
            sb.append(object);

        for( ConstraintViolation<T> fail : valRes)
        {
            sb.append("\n  ").append( fail.getMessage() );
        }
        throw new IllegalArgumentException( sb.toString() );
    }
}// validate()

The Origin.Wise is something like JAXB's @XmlLocation Locator.

查看更多
登录 后发表回答