我有一个在开发/调试阶段在本地运行的 Spring 项目, 在生产过程中,它将加载到 PaaS 上。
我的问题是,根据平台的不同,必须执行某些指令!
目前,我检查从 application.properties
读取的 boolean 值(使用 @ConfigurationProperties
),但我想知道是否有更聪明的方法,因为我也有当我插入生产时更改 boolean 值。
最佳答案
您应该使用 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
}
}
现在您可以通过在逻辑 bean 中执行以下操作来引用逻辑:
@Component
public class Logic {
private @Autowired PlatformDependentLogic platformLogic;
public void doIt() {
doMoreLogic();
platformLogic.platformInstructions();
doWhateverYouWant();
}
}
当然,您可以使用 Spring Boot 特定的 @ConditionalOnProperty
而不是 @Profile
注释,如下所示:
@ConditionalOnProperty(name="your.property", hasValue="dev")
为了更好地理解此注释及其工作原理,您应该阅读 official documentation of @ConditionalOnProperty
关于java - Spring Boot 条件编译/配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39614294/