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