【项目实战】基于SpringBoot实现两个不同SQL数据库实例之间条件迁移

一、背景说明

二、实现方式

@SpringBootApplication
@EnableCaching
@MapperScan("mapper")
@AllArgsConstructor
@Slf4j
public class JoolunTransferApplication {

    public static void main(String[] args) {
        SpringApplication.run(JoolunTransferApplication.class, args);
        ApplicationContext context = SpringContextUtil.getContext();

         log.info("初始化开始");
         long beginTime = SystemClock.now();
         UserInfoService userInfoService = context.getBean(UserInfoService.class);
         userInfoService.initGoUserInfo();
         long totalConsumedTime = SystemClock.now() - beginTime;
         log.info("共使用时间为 totalConsumedTime:[{}]", totalConsumedTime);
         log.info("初始化结束");
    }
}
@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    @SuppressWarnings("static-access")
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        this.context = applicationContext;
    }

    /* 获取静态变量中的ApplicationContext*/
    public static ApplicationContext getContext() {
        return context;
    }

    /*根据bean name 获取对象*/
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) context.getBean(name);
    }

    /*根据Class获取对象*/
    public static <T> T getBean(Class<T> clazz) throws BeansException {
        return context.getBean(clazz);
    }
}