2016-11-28 3 views
0

アプリケーション内のプロパティファイルからプロファイルを有効にしたいとします。結局私は、動的プロファイルをアクティブにしたいが、私は、静的なSpring Bootで@PropertySourceファイルのプロファイルを有効にすることはできますか?

マイアプリ

@SpringBootApplication @PropertySource("classpath:/my.properties") 
public class Application { 

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

    @Component public static class MyBean { 
    @Autowired public void display(@Value("${abc}") String abc) { 
     System.out.println("Post:"+ abc); 
    } 

my.propertiesで始めたいと思います:

spring.profiles.active=STAT 
abc=ABC 

私の出力はmy.propertiesが読み込まれていることの証拠でありますプロファイルは無視されます。

デフォルトプロファイルに戻りません:デフォルト

ディスプレイ:ABC

は、たぶん私は私が達成したいかを説明すべきです。 Springブート前のアプリケーションの動作は、環境によって異なります。たとえば、$ENV=DEV開発環境設定が使用されている場合などです。私はSpringブートに移行して、configにプロファイルを追加したいが、環境を変更しないでください。 私は、私の考えはspring.profiles.active=$ENVmy.propertiesを追加しますが、それはあなたがそれを行うことはできません

答えて

1

んが動作しませんです

if $ENV=DEV then profile DEV is selected

ことを実現します。 @PropertySourceはアプリケーションのブートストラップに影響を与えるほど遅く読み込まれます。

SpringApplicationは、もっと完全なものへのショートカットです。アプリが起動する前に必要なプロパティを読み込んでプロフィールを有効にすることができます。

public static void main(String[] args) { 
    String env = System.getenv().get("ENV"); 
    // Some sanity checks on `env` 
    new SpringApplicationBuilder(Application.class).profiles(env).run(args); 
} 
関連する問題