Spring autowiring order

76 Views Asked by At

I am curretly doing a spring task that recuries me to create bean methods for Video and Channel objects. Each created video must have a localdate with value of one day after the previous one. Everything is ok but there is one problem. I have these variables in my test class

    @Autowired
    Channel channel;

    @Autowired
    Video video;

    @Autowired
    Video otherVideo;

    @Autowired
    Video anotherOtherVideo;

these are created after the channel object so when new Video object is created with the bean it is 3 days of. This is the configuration file

@Configuration
public class ChannelWithInjectedPrototypeVideoConfig {
    private LocalDateTime date = LocalDateTime.of(2023, 10, 1, 10, 0);

    @Bean
    @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public Video video() {
        date = date.plusDays(1);
        return new Video("Cat Failure Compilation", date);
    }

    @Bean
    public Channel channel() {
        Channel channel = new EphemeralChannel();
        for (int i = 0; i < 14; i++) {
            channel.addVideo(video());
        }
        return channel;
    }
}

How can I make it so these three are created before the Channel object (without changing the test class of course)? I tried @DependsOn and @Order but they didn't work. If there are other possible solutions please share them too.

1

There are 1 best solutions below

1
Prophet On

You could move the date variable into the channel block:

@Configuration
public class ChannelWithInjectedPrototypeVideoConfig {

    @Bean
    @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public Video video(LocalDateTime date) {
        return new Video("Cat Failure Compilation", date);
    }

    @Bean
    public Channel channel() {
        LocalDateTime date = LocalDateTime.of(2023, 10, 1, 10, 0);
        Channel channel = new EphemeralChannel();
        for (int i = 0; i < 14; i++) {
            date = date.plusDays(1);
            channel.addVideo(video(date));
        }
        return channel;
    }
}