-1

@Autowired not working, Environment env is always null.

public class MyConstraintValidator implements ConstraintValidator<MyConstraint, String> {
  @Autowired
  private Environment env;

  @Override
  public void initialize(MyConstraint constraintAnnotation) {
     env.resolvePlaceholders(...));
  }

  @Override
  public boolean isValid(String string, ConstraintValidatorContext constraintValidatorContext) {
     return false;
  }
}

Otherwise if use a constructor with parameter Environment and assign it to local Environment env, with @Autowired on the constructor, it is not null. But then the initialize(...) method is not called.

What is the solution?

neblaz
  • 683
  • 10
  • 32

2 Answers2

-1

MyConstraintValidator is not a Bean (ex. @Service, @Component) it can't Autowire other beans. If you need to access some properties from environment, there's a way to put them to static context through implementing EnvironmentAware

Spring Boot - Environment @Autowired throws NullPointerException

Ermintar
  • 1,322
  • 3
  • 22
  • 39
  • It might be a bean through `@Bean`? It doesn't have to be annotated with `@Component`. Also, how do you explain their claim that it works when they use a constructor? – Savior May 13 '20 at 15:03
  • @Savior, looks like spring raises beans for all ConstraintValidator classes via ConstraintValidatorFactory. Just checked a sample with Autowired as in the question above, worked without any issues – Ermintar May 13 '20 at 16:15
  • @neblaz, could you share MyConstraint class? I faced, that initialize block was not called unless MyConstraint contained groups & payload methods. – Ermintar May 13 '20 at 16:18
  • It is basically this example (marked as correct): https://stackoverflow.com/questions/56920934/spring-bean-validation-with-configurable-constraint-values – neblaz May 14 '20 at 06:19
-1

I can't use comments, but you can try referencing this answer about Spring Inversion of Control Container.

It looks like Spring doesn't know about your class, so it doesn't know to auto-inject Environment. You can try annotating it with Spring's @Component and see if that helps.

rlowe8123
  • 31
  • 2