Search code examples
javaspring-bootspring-mvcannotationspojo

using regex from application.yml file and use in pojo class(pattern evaluation)


I tried some approaches :

1. application.yml file

 internationalchar:
      regex:
        expression: "^[\\p{L}\\p{M}\\p{Nd}\\°\\' ]+$"

using in POJO Class

@Pattern(regexp = "${internationalchar.regex.expression}", message = "FSTU_4108,Name")
private String name;

error: Illegal repetition near index 0\r\n${internationalchar.regex.expression}\r\n^"

2.Also tried using escape characters

@Pattern(regexp = "//$//{internationalchar.regex.expression//}", message = "FSTU_4108,Name")

3.Using @Value attribute @Value("${ficoInternationalChar.regex.expression}") Not able to read my regex(giving error that not valid name)

4.

@Value("${internationalchar.regex.expression}")
 private String environment;
 @Pattern(regexp = environment, message = "FSTU_4108,Name")
  private String name;

Attribute value must be constant error(tried making envrionment as final but same error)

NOTE : I am a java beginner


Solution

  • Unfortunately, the @Pattern annotation does not support what you are trying to do. Its regexp attribute does not support placeholders and you must define the regular expression directly.

    If you want to be able the externalise the pattern, you’ll have to implement a custom ConstraintValidator.