admin管理员组文章数量:1530845
场景
应用程序中有多个调度任务。@EnableScheduling
注解放在启动类上可以实现在生产环境下开启全部调度任务。但如果在单元测试中通过"class.method"只实测指定某个调度功能时,使用 @SpringBootTest
注解会开启项目中的全部调度任务,这可能会造成单元测试失败,甚至是数据异常。
@SpringBootApplication
@EnableScheduling
public class VocDataWarehouseSyncApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(VocDataWarehouseSyncApplication.class);
app.setBannerMode(Banner.Mode.OFF);
app.run(args);
}
}
简单的解决方式
做单测时将启动类上的 @EnableScheduling
注释掉,测完交代码时再将注释打开。这个方法是可行的,但是频繁注释会很烦,而且会忘掉。
通过环境变量控制调度开启
将 @EnableScheduling
注解移动到配置类中,如下:
@Configuration
@EnableScheduling
@ConditionalOnProperty(value = "schedule.enable", havingValue = "ture", matchIfMissing = true)
public class ScheduleConfig {
}
上述配置意思是:当环境变量 schedule.enable= true 时,开启调度。如果该环境变量缺失,默认是 true。
这样在生产环境下不需要为此再做任何配置就能保证调度是开启的。
测试环境中只需要配置 schedule.enable= false 就能实现关闭调度。
@Slf4j
@Tag("unit")
@SpringBootTest(properties = {"schedule.enable=false"})
public class CrisisServiceTest {
}
版权声明:本文标题:不同环境下控制@Schedule 开启 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dongtai/1725781688a1042261.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论