LoginSignup
24
27

More than 5 years have passed since last update.

Springでprofileアノテーションによるbeanの切り替え

Posted at

springのprofileの仕組みを利用して、動的にインジェクトされるbeanを切り替える。

とりあえず適当なspring-bootプロジェクトを作る。

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>hoge</groupId>
    <artifactId>springbootexpr2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springbootexpr2</name>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
</project>

適当なinterfaceを作成し、これの実装クラスをいくつか作る。

public interface ProfileSample {
    String getValue();
}
@Component
@Profile("default")
public class DefaultProfile implements ProfileSample {

    public String getValue() {
        return "default";
    }

}

profileは未指定のデフォルト値はdefaultになっている。そのため、profileアノテーションにその値を指定すると、profile未指定時にはこのクラスが使われる。

@Component
@Profile("dev")
public class DevProfile implements ProfileSample {

    public String getValue() {
        return "dev";
    }

}
@Component
@Profile("production")
public class ProductionProfile implements ProfileSample {

    public String getValue() {
        return "production";
    }

}

起動用のクラスに上で作成したinterfaceをインジェクションさせる。

@Controller
@EnableAutoConfiguration
@ComponentScan
public class SampleController {

    @Autowired
    ProfileSample sample;

    @RequestMapping("/")
    @ResponseBody
    String home() {
        System.out.println(sample.getValue());
        return "Hello World!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SampleController.class, args);
    }
}

あとはspring.profiles.activeプロパティをどこかで指定すればそのプロファイルが、未指定であれば上で触れたようにdefaultが、使用される。

プロファイルの指定はコマンドライン引数ではこんな感じ。

--spring.profiles.active=dev

プロパティファイル、例えばapplication.yamlで指定する場合はこんな感じ。

application.yaml
spring.profiles.active: production

ちなみにプロパティ指定の方法は沢山あるのでその一覧と優先順位については https://docs.spring.io/spring-boot/docs/2.0.0.M4/reference/htmlsingle/#boot-features-external-config

なお、この例程度の内容なら、interfeceのデフォルトメソッドで十分だったりする。

24
27
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
24
27