LoginSignup
0
0

More than 5 years have passed since last update.

@ConditionalOnExpressionとSpELの正規表現でbeanを切り替える

Last updated at Posted at 2019-01-11

たとえば、spring-bootのプロパティファイルの値に基づいて登録されるbeanを切り替えたい、とする。加えて、そのプロパティ値がある正規表現にマッチした場合に応じて、登録されるbeanを切り替えたい。

この場合は@ConditionalOnExpressionのSpELで正規表現を使用する。

ソースコード

プロパティファイル

いま、あるプロパティ値がv0001からv0004を取り得るとする。

src/main/resources/application.yml
oncondition:
#  value: v0001
#  value: v0002
#  value: v0003
  value: v0004

このとき、v0001からv0003の場合と、v0004の場合で、beanを切り替えたい、とする。

切り替えられるクラス

適当な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はSpELがマッチする場合に有効となる。ここでは${oncondition.value}でプロパティを参照し、正規表現matches 'v000[123]'を記述している。これによって、oncondition.valuev0001,v0002,v0003の場合にこのクラスが有効になる。

実行

最後に確認するための起動用クラス。

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());
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0