1

我打算ConstraintValidationjavax-validationAPI使用

pom.xml

<dependency>
      <groupId>javax.el</groupId>
      <artifactId>javax.el-api</artifactId>
      <version>3.0.0</version>
    </dependency>
    <dependency>
      <groupId>org.glassfish.web</groupId>
      <artifactId>javax.el</artifactId>
      <version>2.2.6</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate.validator</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>6.0.2.Final</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate.validator</groupId>
      <artifactId>hibernate-validator-annotation-processor</artifactId>
      <version>6.0.2.Final</version>
    </dependency>
    <dependency>
      <groupId>javax.validation</groupId>
      <artifactId>validation-api</artifactId>
      <version>2.0.0.Final</version>
    </dependency>

PositionCheck.java

@Constraint(validatedBy = PositionValidator.class)
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface PositionCheck {
    String message() default "Invalid position.";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

PositionValidator.java

public class PositionValidator implements ConstraintValidator<PositionCheck, Position> {
    public void initialize(PositionCheck positionCheck) {
        System.out.println(positionCheck);
    }

    public boolean isValid(Position position, ConstraintValidatorContext constraintValidatorContext) {
        return position.getX() > 0
                && position.getY() > 0
                && position.getX() < BOARD_X_SIZE
                && position.getY() < BOARD_Y_SIZE;
    }
}

位置.java

// Generates all the getter methods
@Getter(AccessLevel.PUBLIC)

// Generate all the setter methods
@Setter(AccessLevel.PUBLIC)

// Generates an all argument constructor
@AllArgsConstructor(access = AccessLevel.PUBLIC)

// Overrides the default toString() method
@ToString(callSuper = true, includeFieldNames = true)

// Overriding equals() and hashCode() methods, to check the equality
@EqualsAndHashCode
public class Position {

    // position on the x-axis
    private Integer x;

    // position on the y-axis
    private Integer y;

    // direction indicates, what direction robot is facing
    // possible values are NORTH, SOUTH, EAST or WEST
    private Direction direction;
}

机器人.java

@Getter @Setter(AccessLevel.PUBLIC)
@NoArgsConstructor(access = AccessLevel.PUBLIC)

public class Robo implements IRobo {


    @PositionCheck
    private Position currentPosition;

    public void left() {

    }

    public void move() {

    }

    @SneakyThrows(InvalidPositionException.class)
    public void place(Position position) {
        if(position == null) {
            throw new InvalidPositionException("To place robo on TableTop, position cannot be null");
        }

        this.setCurrentPosition(new Position(position.getX(), position.getY(), position.getDirection()));
    }

    public void report() {

    }

    public void right() {

    }
}

应用程序.java

public class App 
{
    public static void main( String[] args ) {
        Robo robo = new Robo();
        Position position = new Position(0,6, Direction.NORTH);
        robo.setCurrentPosition(position);
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<Position>> constraintViolations = validator.validate(position);
        for (ConstraintViolation<Position> constraint : constraintViolations) {
            System.out.println(constraint.getPropertyPath() + "  "
                    + constraint.getMessage());
        }
    }
}

这里的问题是,isValid()方法 onPositionCheckValidator没有被调用。我在这里想念什么?

4

1 回答 1

1

您正在验证position.

注释@PositionCheck在 的字段currentPositionrobo。Validate robo,验证器将被调用。

于 2018-04-15T13:00:32.003 回答