Spring Boot条件编译/配置

时间:2016-09-21 10:41:55

标签: java spring gradle

我有一个在开发/调试阶段在本地运行的Spring项目, 在生产时,它将被加载到PaaS上。

我的问题是必须根据平台执行某些指令!

目前我检查了一个我从@ConfigurationProperties读取的布尔值(使用application.properties),但我想知道是否有更聪明的方法,因为当我推进生产时我还要更改布尔值

2 个答案:

答案 0 :(得分:1)

你应该使用Spring配置文件并实现你的检查有点面向对象:

我假设您的代码看起来像这样,Logic是一个Spring托管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
    }
}

现在您可以在Logic bean中执行此操作来引用逻辑:

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

当然,您可以使用特定的弹簧启动@ConditionalOnProperty而不是@Profile注释,如下所示:

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

为了更好地理解这个注释及其工作方式,您应该阅读official documentation of @ConditionalOnProperty

答案 1 :(得分:0)

我建议您为本地/ Paas环境使用Gradle产品口味,类似于: https://code.tutsplus.com/tutorials/using-gradle-build-variants--cms-25005

相关问题