Skip to content

Instantly share code, notes, and snippets.

@mitoma
Last active February 8, 2017 12:43
Show Gist options
  • Save mitoma/dbcf5e7945c2a2bbcd2b130a2ec756fd to your computer and use it in GitHub Desktop.
Save mitoma/dbcf5e7945c2a2bbcd2b130a2ec756fd to your computer and use it in GitHub Desktop.
やりたいこと

やりたいこと

以下のように ControllerA から呼び出される場合と ControllerB で呼び出される場合で DbRepository と InMemoryRepository を呼び出しわけたい。(各Repositoryは共通のインターフェイスを実装している)

  • ControllerA#get() → ServiceX#doSomething() → DbRepository#findById()
  • ControllerB#get() → ServiceX#doSomething() → InMemoryRepository#findById()

知っているやり方(@Qualifier)

この場合はそれぞれ以下のようにすれば期待する動作になる。

  • ServiceA に DbRepository を Inject して “serviceX_forControllerA” と名前をつけたオブジェクトを ControllerA に名前指定して Inject
  • ServiceB に InMemoryRepository を Inject して “serviceX_forControllerB” と名前をつけたオブジェクトと ControllerB に名前指定して Inject

避けたいと思っていること

ServiceX に Repository を切り替えるコードを入れる事。(FactoryをInjectするのもそういう意味で少し微妙に感じている)

めんどうに思っていること

当然 ComponentScan で複数のオブジェクトグラフを作ることはできないので、ここだけ XML か JavaConfig で名前付きのオブジェクトグラフを作らなければならない。

知りたいこと

この面倒さが、必要な面倒さなのか、別のやり方で回避できるのか。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment