View Javadoc
1   package top.infra.test.containers;
2   
3   import com.google.common.collect.Maps;
4   
5   import lombok.SneakyThrows;
6   
7   import org.springframework.context.ApplicationContextInitializer;
8   import org.springframework.context.ConfigurableApplicationContext;
9   import org.testcontainers.containers.GenericContainer;
10  
11  import java.util.Map;
12  import java.util.Map.Entry;
13  import java.util.function.BiFunction;
14  
15  public class GenericContainerInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
16  
17      private static final Map<GenericContainer, BiFunction<GenericContainer, ConfigurableApplicationContext, Void>> //
18          containers = Maps.newLinkedHashMap();
19  
20      public static void onInitialize(
21          final GenericContainer container, //
22          final BiFunction<GenericContainer, ConfigurableApplicationContext, Void> callback //
23      ) {
24          containers.put(container, callback);
25      }
26  
27      @SneakyThrows
28      @Override
29      public void initialize(final ConfigurableApplicationContext applicationContext) {
30          for (final Entry<GenericContainer, BiFunction<GenericContainer, ConfigurableApplicationContext, Void>> entry :
31              containers.entrySet()) {
32              final GenericContainer container = entry.getKey();
33              if (container.getContainerId() != null) {
34                  final BiFunction<GenericContainer, ConfigurableApplicationContext, Void> callback = entry.getValue();
35                  callback.apply(container, applicationContext);
36              }
37          }
38      }
39  }