Spring boot : Override property value reader

539 views Asked by At

I am using Spring's @PropertySource and @ConfigurationProperties to read the properties from a file. Below are the sample properties:

patterns[0]=\b(test1)\b
patterns[1]=\b(test2)\b

Below is the class that reads these properties:

@Configuration
@PropertySource("classpath:patterns.properties")
@ConfigurationProperties
public class PatternConfig {

    private List<String> patterns;
    //Getters and Setters
}

This reads the properties as expected and sets the values in patterns list. However, what I really want to do is, to compile the pattern before it gets added and then add it into the list of Patterns. E.g. the new list will be

private List<Pattern> patterns;

So, I need to override something which would call Pattern.compile on string property and return Pattern object which would then get added into the list. Is it possible?

1

There are 1 answers

4
PaulNUK On

Create a method in this configuration that returns the list of patterns, annotate it with @Bean, and do the pattern compile within the method.

@SpringBootApplication
@EnableConfigurationProperties
@Import(PatternConfig.class)
public class DemoApplication {

  public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
  }
}


@Configuration
@PropertySource("classpath:patterns.properties")
@ConfigurationProperties
class PatternConfig {


  public void setPatterns(List<String> patterns) {
      this.patterns = patterns;
  }

  private List<String> patterns;

  public List<String> getPatterns() {
      return patterns;
  }

  @Bean
  public List<Pattern> compiledPatterns() {

      List<Pattern> compiledPatterns = new ArrayList<>();
      for (String pattern : patterns) {
        compiledPatterns.add(
                Pattern.compile(pattern));
      }
      return compiledPatterns;
  }

}