Profileアノテーションとは
Spring Bootには設定を切り替えるProfileアノテーションという仕組みがあります。
調べてみると開発時と本番稼働時の設定を切り替えたい場合に使用すると書いてあります。
Profileアノテーションは実装そのものを入れ替えることができるので上記のような設定の変更だけではなくカスタマイズのために使用することもできます。
例えば、パスワードリマインダーのような仕組みでUI(画面)はそのままでユーザー管理の対象をLDAPとデータベースと入れ替えることができます。
Profileアノテーションの実装
getValue()というメソッドで文字列を返すだけの簡単なサンプルを作成します。
- ProfileValue.java
package com.sios.ex.springboot;
public interface ProfileValue {
String getValue();
}
インターフェースを定義します。
- DefaultValue.java
package com.sios.ex.springboot;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Component
@Profile("default")
public class DefaultValue implements ProfileValue {
@Override
public String getValue() {
return "Default";
}
}
Beanを定義します。ここでは@Profileにdefaultを指定しています。
設定がない場合はdefaultが使用されます。
- DevelopValue.java
package com.sios.ex.springboot;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Component
@Profile("develop")
public class DevelopValue implements ProfileValue {
@Override
public String getValue() {
return "Develop";
}
}
こちらでは@Profileにdevelopが指定してあります。
- MainController.java
package com.sios.ex.springboot;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class MainController {
@Autowired
private ProfileValue value;
@GetMapping("/")
public String indexForm(Model model) {
model.addAttribute("value", value.getValue());
return "index";
}
}
Profileアノテーションを使ったBeanの使用方法です。
11~12行でBeanを宣言しています。設定によりDefaultValueクラスかDevelopValueクラスのいずれかのオブジェクトが使用されます。
- index.html
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Sample</title>
</head>
<body>
<p th:text="${value}"></p>
</body>
</html>
ブラウザにMainControllerクラスのindexFormメソッドで設定されたvalueを表示します。
Profileの設定
application.propertiesファイルのspring.profiles.activeに使用するProfileを指定します。
何も指定しないときはdefaultが指定されたとみなされてブラウザにはDefaultが表示されます。
サンプルプログラムでdevelopを指定するときはapplication.propertiesに次のように指定します。
- application.properties
spring.profiles.active=develop
ブラウザにはDevelopが表示されます。

