2016-11-28 102 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引導並將配置文件放到配置文件中,但我希望保持環境不變。 我想實現一個

if $ENV=DEV then profile DEV is selected

我的想法是添加my.propertiesspring.profiles.active=$ENV,但它不工作

回答

1

不,你不能這樣做。 @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); 
} 
相關問題