最快速的构建spring context,快速的进行开发测试

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();

完整源代码: https://gitee.com/quzsc/spring-context-demo

posted @ 2022-02-12 22:05  飞翔的理念  阅读(72)  评论(0编辑  收藏  举报