2016-09-21 287 views
0

我有一個在開發/調試階段本地運行的Spring項目, 生產期間它將加載到PaaS上。Spring Boot條件編譯/配置

我的問題是,有一定的指令,必須執行取決於平臺!

目前我檢查一個布爾值(使用@ConfigurationProperties),我從application.properties讀取,但我想知道是否有更聰明的方法,因爲我還需要在生產中更改布爾值。

+0

什麼樣的「指示」?你的意思是配置屬性不同,或者你需要執行一些實際的代碼取決於env? – rorschach

+1

你可以試試Spring配置文件。 –

回答

1

你應該使用Spring配置文件和實現支票面向一點點鐵道部對象:

我假設你的代碼看起來像這樣,和Logic是彈簧託管bean:

@Component 
public class Logic { 
    public void doIt() { 
     doMoreLogic(); 
     if (yourProperty == true) { 
      your(); 
      certain(); 
      instructions(); 
     } 
     doWhateverYouWant(); 
    } 
} 

如果提取一定的邏輯的一類,那麼你就可以做到這一點更多的面向對象的方法:

public interface PlatformDependentLogic { 
    void platformInstructions(); 
} 

@Component @Profile("dev") 
public class DevLogic implements PlatformDependentLogic { 
    public void platformInstructions() { 
     your(); 
     certain(); 
     instructions(); 
    } 
} 
@Component @Profile("!dev") 
public class NoopLogic implements PlatformDependentLogic { 
    public void platformInstructions() { 
     // noop 
    } 
} 

現在你可以在你的邏輯豆這樣引用的邏輯:

@Component 
public class Logic { 
    private @Autowired PlatformDependentLogic platformLogic; 
    public void doIt() { 
     doMoreLogic(); 
     platformLogic.platformInstructions(); 
     doWhateverYouWant(); 
    } 
} 

當然你也可以利用彈簧啓動特定@ConditionalOnProperty代替@Profile註釋像這樣的:

@ConditionalOnProperty(name="your.property", hasValue="dev") 

爲了更好地理解這個註釋的,以及它如何workds你應該閱讀official documentation of @ConditionalOnProperty