SpringBoot 项目启动过程都需要几十秒。开发过程中反复测试很浪费时间。运行单元测试也比较浪费时间。
今天发现一个SpringBoot自己写单元测试类 StaticApplicationContext ,或然开朗。使用下面的代码,启动速度快,最适合测试DAO,Service等。
StaticApplicationContext context = new StaticApplicationContext();
context.getBeanFactory().registerSingleton("dataSource", dataSource);
context.refresh();
context.start();
DataSource dataSource = context.getBean(DataSource.class);
log.info("dataSource:" + dataSource);
context.stop();
StaticApplicationContext context = new StaticApplicationContext();
context.getBeanFactory().registerSingleton("dataSource", dataSource);
context.registerSingleton("autowiredAnnotationBeanPostProcessor", AutowiredAnnotationBeanPostProcessor.class);
context.registerSingleton("userService", UserService.class);
context.refresh();
context.start();
UserService userService = context.getBean(UserService.class);
int userCount = userService.getUserCount();
log.info("userCount:" + userCount);
context.stop();