@value属性在spring组件中返回null

b5buobof  于 2021-08-25  发布在  Java
关注(0)|答案(2)|浏览(370)

我在SpringBoot中创建了一个验证程序组件,并在 application.properties . 我用过 @Value 注解来获取组件中regex的值,我在任何方法或构造函数之外编译模式,这给了我null指针异常,因为regex当时没有获取它的值。但当我将模式移动到某个方法时,它运行良好。为什么呢?为什么即使对象是使用@component创建的,@value也不起作用
请看下面的代码:
返回nullpointerexception的代码:

@Component
public class ValidString implements ConstraintValidator<ValidString, String> {

  @Value("${user.input.regex}")
  private String USER_INPUT_REGEX;

  private Pattern USER_INPUT_PATTERN = Pattern.compile(USER_INPUT_REGEX);

  @Override
  public boolean validate(String userInput, ConstraintValidatorContext constraintValidatorContext) {
    return USER_INPUT_PATTERN.matcher(userInput).find();
  }
}

工作守则罚款:

@Component
public class ValidString implements ConstraintValidator<ValidString, String> {

  @Value("${user.input.regex}")
  private String USER_INPUT_REGEX;

  private Pattern USER_INPUT_PATTERN;

  @Override
  public boolean validate(String userInput, ConstraintValidatorContext constraintValidatorContext) {
    USER_INPUT_PATTERN = Pattern.compile(USER_INPUT_REGEX);
    return USER_INPUT_PATTERN.matcher(userInput).find();
  }
}

另外,如果你能解释为什么第一个不起作用,第二个起作用,那就太好了。
应用程序属性

user.input.regex = ^[a-zA-Z0-9/\\-_ \\s+]*$
pdtvr36n

pdtvr36n1#

字段初始值设定项(问题中的第一个示例)在类构造函数执行期间执行。 @Value 在构造函数返回后,使用反射由spring注入。这意味着您不能让初始值设定项使用 @Value -注入值。
该问题可以通过构造函数或setter注入来解决:

// Inject using constructor
@Component
public class ValidString implements ConstraintValidator<ValidString, String> {

  private Pattern USER_INPUT_PATTERN;

  @Autowired
  public ValidString(@Value("${user.input.regex}") String regex) {
    this.USER_INPUT_PATTERN = Pattern.compile(regex);
  }
// Inject using setter method
@Component
public class ValidString implements ConstraintValidator<ValidString, String> {

  private Pattern USER_INPUT_PATTERN;

  @Autowired
  private void setUserInputRegex(@Value("${user.input.regex}") String regex) {
    this.USER_INPUT_PATTERN = Pattern.compile(regex);
  }
gcuhipw9

gcuhipw92#

模式用户\输入\模式在spring进程之前。类validstring对象的初始顺序是:->processfieldinitial->constructor->injectfield,所以当您使用1个代码时,它必须是null点,因为字段没有inject

相关问题