Sprig BootでProfile切り替え

Springの起動引数でBeanを切り替えたい


切り替え対象のBeanが実装するインターフェース

package hello;

public interface GreedInterface {
    public String greed();
}

実装クラス。@Profileアノテーションで切り替えに使うプロファイル名を指定する。

package hello.impl;

import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

import hello.GreedInterface;

@Profile("hello")
@Service
public class HelloService implements GreedInterface {

	@Override
	public String greed() {
		return "hello";
	}

}
package hello.impl;

import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

import hello.GreedInterface;

@Profile("hi")
@Service
public class HiService implements GreedInterface {

	@Override
	public String greed() {
		return "Hi";
	}

}

呼び出し側のメインクラス。GreedInterfaceをAutowireする。

package hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application implements CommandLineRunner {
    
    @Autowired
    GreedInterface greedInterface;

    public static void main(String[] args) throws Exception {
        SpringApplication application = new SpringApplication(Application.class);
	application.setShowBanner(false);
	application.run(args);
    }

    @Override
    public void run(String... args) throws Exception {
	System.out.println(greedInterface.greed());
    }
}

application.propertiesにデフォルトのプロファイル名を指定する。

spring.profiles.active=hello

実行時に起動引数でプロファイルを変える。

$ java -jar gs-spring-boot-0.1.0.jar --spring.profiles.active=hi
Hi

$ java -jar gs-spring-boot-0.1.0.jar --spring.profiles.active=hello
hello