理系学生日記

おまえはいつまで学生気分なのか

SpringでBean名にエイリアスの名前を付ける

既存の Spring アプリケーションにおいて applicationContext.xml で特定の Bean が定義されており、それを別名の Bean として参照したい場合がある。 今回遭遇したケースでは - ロジック層用の applicationContext.xml が存在していて多数の Bean が定義されており、 - それを Spring Batch の context から参照したい という状況があった。 具体的に言うと、Spring Batch の設定ファイルでは記述を簡潔にするため、頻繁に依存する Bean 名のデフォルト値が設定されており、

Configuring and Running a Job> The JobRepositoryFactoryBean tries to auto-detect the database type from the DataSource if it is not specified. << このデフォルト値に合わせておけば、設定ファイルにグダグダと明示的に Bean 名を指定しなくても良いわけなのだけれど、ロジック層ではそのデフォルト値に合致しない名称で Bean が定義されてしまっている。

Spring Core では、こういう場合に使用できるよう、Bean 名には Alias が張れるようになっている。「Aliasing a bean outside the bean definition」より。

Core Technologies> This is commonly the case in large systems where configuration is split amongst each subsystem, each subsystem having its own set of object definitions. In XML-based configuration metadata, you can use the element to accomplish this. << 実際の書き方としては、 |xml| ||< としておけば、fromName という Bean を toName で参照できて便利。