2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Spring Boot2で環境毎にInjection対象を変える

Posted at

はじめに

Spring Bootで@Autowiredでinjectionしますが、環境毎に読み込む対象を変えたいというケースがあった場合の対応について書きます。

ここでいう環境とはSpring Boogの起動引数spring.profiles.activeのことで、この起動引数を変えた場合に読み込むクラスを変えるという話です。

環境

Java10
Spring Boot2.0.4.RELEASE

ちょっと前に作ったものなので、環境が古いですがJava11とBoot2.1系でもこれで動くはずです。

interfaceを用意する

まずはinterface(abstract classでも可)を用意します。

public interface TestInterface {
    void print();
}

interfaceの実体を用意する

環境毎に読み込む対象を変えたいということで先ほどのinterfaceをimplementsしたクラスを2つ生成します。

この2つのクラスを起動引数によって変更します。
引数にはtestとtest2`を与えるとします。

@Service
@Profile("test")
public class TestServiceA implements TestInterface {
    public void print() {
        System.out.println("test");
    }
}
@Service
@Profile("test2")
public class TestServiceB implements TestInterface {
    public void move() {
        System.out.println("test2");
    }
}

@Profileを付けるだけです。
これを付けておくと起動引数が合わない場合はBean化対象とされません。

使う側の実装

今回はControllerからこのクラスを使用します。

@Controller
public class TestController {
    @Autowired
    private TestInterface testInterface;

    // Controllerの処理
}

対象のクラスをinterfaceにするだけです。
ProfileにてBeanとなっている対象が1つのみとなっているため、起動引数によって対象が変わります。

2
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?