如何在不修改测试类的前提下让Spring中Video Bean先于Channel Bean初始化?
解决方案
方案1:重构日期生成逻辑,摆脱创建顺序依赖
用单例原子计数器替代类变量维护日期偏移,既保证按顺序生成日期,又避免多线程问题,同时可通过依赖初始化确保测试用Video先创建。
// 定义单例计数器Bean @Bean public AtomicInteger videoDayCounter() { return new AtomicInteger(0); } // Prototype的Video Bean方法,依赖计数器生成日期 @Bean @Scope("prototype") public Video video(AtomicInteger videoDayCounter) { LocalDateTime date = LocalDateTime.now().plusDays(videoDayCounter.getAndIncrement()); return new Video(date); } // 定义空初始化Bean,触发三个测试用Video实例提前创建 @Bean public VideoPreInitializer videoPreInitializer(Video video1, Video video2, Video video3) { return new VideoPreInitializer(); } // Channel Bean依赖初始化Bean,确保测试用Video先被创建 @Bean @DependsOn("videoPreInitializer") public Channel channel() { Channel channel = new Channel(); for (int i = 0; i < 14; i++) { channel.addVideo(video()); } return channel; } // 空类,仅用于触发依赖注入 class VideoPreInitializer {}
方案2:手动提前创建测试用Video实例
利用Spring上下文在Channel创建前手动生成三个Video实例,抢占前3天的日期序列:
@Configuration public class AppConfig implements ApplicationContextAware { private ApplicationContext context; private LocalDateTime date = LocalDateTime.now(); @Override public void setApplicationContext(ApplicationContext context) throws BeansException { this.context = context; } @Bean public Channel channel() { // 提前创建三个Video实例,占用前3天日期 context.getBean(Video.class); context.getBean(Video.class); context.getBean(Video.class); Channel channel = new Channel(); for (int i = 0; i < 14; i++) { channel.addVideo(context.getBean(Video.class)); } return channel; } @Bean @Scope("prototype") public Video video() { date = date.plusDays(1); return new Video(date); } }
方案3:隔离测试与Channel的日期生成逻辑
直接给Channel内的Video指定起始日期,跳过测试用的3天,让两者日期序列互不干扰:
@Bean @Scope("prototype") public Video video(LocalDateTime date) { return new Video(date); } @Bean public Channel channel() { Channel channel = new Channel(); // 从第4天开始生成Channel内的Video LocalDateTime startDate = LocalDateTime.now().plusDays(3); for (int i = 0; i < 14; i++) { channel.addVideo(video(startDate.plusDays(i))); } return channel; } // 单独定义测试用的三个Video Bean,使用前3天日期 @Bean public Video testVideo1() { return video(LocalDateTime.now()); } @Bean public Video testVideo2() { return video(LocalDateTime.now().plusDays(1)); } @Bean public Video testVideo3() { return video(LocalDateTime.now().plusDays(2)); }
内容的提问来源于stack exchange,提问作者Newbee
相关产品推荐
相关产品推荐

