2016-09-21 290 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