[JAVA] Switch beans with @ConditionalOnExpression and SpEL regular expressions

For example, suppose you want to switch beans that are registered based on the values in the spring-boot properties file. In addition, I want to switch the registered bean depending on when the property value matches a certain regular expression.

In this case, use a regular expression in SpEL of @ ConditionalOnExpression.

Source code

Property file

Now suppose a property value can take `v0004``` from` v0001```.

src/main/resources/application.yml


oncondition:
#  value: v0001
#  value: v0002
#  value: v0003
  value: v0004

At this time, it is assumed that the bean is to be switched between the case of `` v0001``` to v0003``` and the case of `v0004```.

Classes that can be switched

Make a suitable interface.

public interface ISample {
    String value();
}
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Component;

@Component
@ConditionalOnExpression("#{'${oncondition.value}' matches 'v000[123]'}")
public class Value123 implements ISample {
    @Override
    public String value() {
        return "value123";
    }
}
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Component;

@Component
@ConditionalOnExpression("#{'${oncondition.value}' matches 'v0004'}")
public class Value4 implements ISample {
    @Override
    public String value() {
        return "value4";
    }
}

@ConditionalOnExpression is enabled when SpEL matches. here${oncondition.value}Browse the properties with the regular expression matches'v000[123]'Is described. This makes oncondition.value is v0001,v0002,This class is valid for v0003.



## Run
 The startup class to check at the end.

```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App implements CommandLineRunner {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

    @Autowired
    ISample hoge;
    
    @Override
    public void run(String... args) throws Exception {
        System.out.println(hoge.value());
    }
}

Recommended Posts

Switch beans with @ConditionalOnExpression and SpEL regular expressions
colorize and regular expressions
Distinguish between integers and decimals with regular expressions
[Ruby] Exclude and replace specific patterns with regular expressions
Parse Japanese addresses with regular expressions
Easily make troublesome regular expressions with Rubular
Easy to trip with Java regular expressions
switch and EnumMap
Switch environment with Spring Boot application.properties and @Profile annotation
[RSpec] WebMock handles regular expressions and Array query strings