Home > front end >  Field annotated with @Value is returning null
Field annotated with @Value is returning null

Time:06-17

I am using ConstraintValidator implementation to validate if character is above certain height defined in application.properties and I have encountered a problem where the field minimumHeight with @Value is always null. I have also tried constructor injection but then it gives out error as follows:

java.lang.NoSuchMethodException: com.miquido.Validator.CharacterValidator.<init>()
at java.base/java.lang.Class.getConstructor0(Class.java:3585) ~[na:na]
at java.base/java.lang.Class.getConstructor(Class.java:2271) ~[na:na]
at org.hibernate.validator.internal.util.privilegedactions.NewInstance.run(NewInstance.java:41) ~[hibernate-validator-6.2.3.Final.jar:6.2.3.Final]

This is my validator:

import org.springframework.beans.factory.annotation.Value;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;


public class CharacterValidator implements ConstraintValidator<ValidCharacter, Long> {

    @Value("${character.minimum}")
    private Long minimumHeight;

    @Override
    public boolean isValid(Long value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }
        formatMessage(context);
        return value >= minimumHeight;
    }

    private void formatMessage(ConstraintValidatorContext context) {
        String msg = context.getDefaultConstraintMessageTemplate();
        String formattedMsg = String.format(msg, this.minimumHeight);
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(formattedMsg)
                .addConstraintViolation();
    }
}

    @Target({ElementType.FIELD})
    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validatedBy = CharacterValidator.class)
    public @interface ValidCharacter {
    
        String message() default "Character must be higher than %s";
    
        Class<?>[] groups() default {};
    
        Class<? extends Payload>[] payload() default {};
    }

EDIT I have edited my code as @antey13 suggested, but still the minimumHeight is null.

CodePudding user response:

Remove the constructor and add generic params ConstraintValidator<ValidCharacter, String>. Make sure that you are using spring validation (spring-boot-starter-validation for spring boot), because in another case @Value won't work because spring will not be aware of your validator class

CodePudding user response:

Try adding @Component on CharacterValidator class

CodePudding user response:

Could you check the following bullet points?

  • The file is loaded in the correct way
  • CharacterValidator is a bean of Spring
  • The class has a correct construct
  • initialize method exists (the error in this question seems to be for this method)
    @Override
    public void initialize(ContactNumberConstraint contactNumber) {
    }

You can follow the next links:

  1. https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-constraint-validator
  2. https://www.baeldung.com/spring-mvc-custom-validator
  • Related