25
25

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フレームワークにて、アノテーションベースConfigurationでプロファイルを設定し利用する方法

Posted at

Spring DI

Configuration

SpringフレームワークではDIコンテナに対してConfigurationと言う設定ファイルを渡し、「こんな時には、このインスタンスを返してね」と設定する。そのConfigurationファイルの種類は3つある。

  • JavaベースConfiguration
  • XMLベースConfiguration
  • アノテーションベースConfiguration

以下ではアノテーションベースのConfigurationについて説明する。

アノテーションベースのConfiguration

@Configuration

Configurationクラスであることを表す。

AppConfig
package com.example;

@Configuration
public class AppConfig {

}

@Component

DIコンテナに管理させるBeanとして、クラスを登録する。

User
package com.example;

@Component
public class User {

  public String getName(){
    ...
  }

}

@ComponentScan

@Componentが付与されたクラスをスキャンし、BeanとしてDIに登録する。スキャン対象は、パッケージとして指定することができる。先ほどのAppConfigクラスに対して、設定を行うと以下のようになる。

Configuration
package com.example;

@Configuration
@ComponentScan("com.example")
public class AppConfig {

}

アノテーションベースConfigurationのサンプルコード

以上のアノテーションを使用してDIコンテナを利用すると、以下のようなコードになる。

DemoIoC
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クラス階層を以下の様に変更してプロファイルを設定してみる。

User
package com.example;

public interface User {
  public String getName();
}
UserDummy
package com.example;

@Component
@Profile("dev") // devという名前でプロファイルを設定
public class UserDummy implements User {
  ...
}
UserMaster
package com.example;

@Component
@Profile("test") // testという名前でプロファイルを設定
public class UserImpl implements User {
  ...
}

Profileの利用例

以上のUserクラス階層を、プロファイルを設定して利用してみる。

DemoIoC
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())
  }
}
25
25
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
25
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?