Spring DI
Configuration
SpringフレームワークではDIコンテナに対してConfigurationと言う設定ファイルを渡し、「こんな時には、このインスタンスを返してね」と設定する。そのConfigurationファイルの種類は3つある。
- JavaベースConfiguration
- XMLベースConfiguration
- アノテーションベースConfiguration
以下ではアノテーションベースのConfigurationについて説明する。
アノテーションベースのConfiguration
@Configuration
Configurationクラスであることを表す。
package com.example;
@Configuration
public class AppConfig {
}
@Component
DIコンテナに管理させるBeanとして、クラスを登録する。
package com.example;
@Component
public class User {
public String getName(){
...
}
}
@ComponentScan
@Componentが付与されたクラスをスキャンし、BeanとしてDIに登録する。スキャン対象は、パッケージとして指定することができる。先ほどのAppConfigクラスに対して、設定を行うと以下のようになる。
package com.example;
@Configuration
@ComponentScan("com.example")
public class AppConfig {
}
アノテーションベースConfigurationのサンプルコード
以上のアノテーションを使用してDIコンテナを利用すると、以下のようなコードになる。
package com.example;
public class DemoIoC {
public static void main(String args[]){
// DIコンテナを構築し、Configurationファイルを渡す
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
// Beanを取得
User user = context.getBean(User.class);
System.out.println(User.getName())
}
}
Profile設定
SpringフレームワークではConfigurationをグループ化して、プロファイルとして管理することができる。例えば、開発用のConfiguration、テスト用のConfiguration、製品用のConfigurationと、分けて管理し、Configurationを簡単に切り替えることができる。
@Profile
プロファイルを設定する。先ほどのUserクラス階層を以下の様に変更してプロファイルを設定してみる。
package com.example;
public interface User {
public String getName();
}
package com.example;
@Component
@Profile("dev") // devという名前でプロファイルを設定
public class UserDummy implements User {
...
}
package com.example;
@Component
@Profile("test") // testという名前でプロファイルを設定
public class UserImpl implements User {
...
}
Profileの利用例
以上のUserクラス階層を、プロファイルを設定して利用してみる。
package com.example;
public class DemoIoC {
public static void main(String args[]){
// DIコンテナを構築
// プロファイルとしてdevを設定
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext();
context.register(AppConfig.class);
context.getEnvironment().addActiveProfile("dev");
context.refresh();
// Beanを取得
// userの実装はUserDummy
User user = context.getBean(User.class);
System.out.println(User.getName())
}
}