Interface ServiceDependencies


  • public interface ServiceDependencies
    Specifies dependencies between services.

    When starting a server, Ratpack will extract all instances of ServiceDependencies from the server registry. Each will be called with a spec that they can use to define the dependencies between services.

    Services are guaranteed to start after and stop before their dependencies. Services that do not have a dependency relationship may start and stop concurrently. If a depended on service fails to start, the dependent service will not be started.

    
     import ratpack.core.server.ServerConfig;
     import ratpack.core.server.RatpackServer;
     import ratpack.core.service.Service;
     import ratpack.core.service.ServiceDependencies;
     import ratpack.core.service.StartEvent;
     import ratpack.core.service.StopEvent;
    
     import java.util.ArrayList;
     import java.util.List;
    
     import static java.util.Arrays.asList;
     import static org.junit.jupiter.api.Assertions.assertEquals;
    
     public class Example {
    
       private static final List<String> EVENTS = new ArrayList<>();
    
       private static class MyService implements Service {
    
         private final String label;
    
         public MyService(String label) {
           this.label = label;
         }
    
         public String getLabel() {
           return label;
         }
    
         @Override
         public void onStart(StartEvent event) throws Exception {
           EVENTS.add(label + "-start");
         }
    
         @Override
         public void onStop(StopEvent event) throws Exception {
           EVENTS.add(label + "-stop");
         }
       }
    
       public static void main(String[] args) throws Exception {
         RatpackServer server = RatpackServer.of(s -> s
           .serverConfig(ServerConfig.embedded())
           .registryOf(r -> r
             .add(new MyService("one"))
             .add(new MyService("two"))
             // service two depends on service one
             .add(ServiceDependencies.class, d -> d.dependsOn(
               MyService.class, service -> service.getLabel().equals("two"),
               MyService.class, service -> service.getLabel().equals("one")
             ))
           )
         );
    
         server.start();
         assertEquals(asList("one-start", "two-start"), EVENTS);
    
         server.stop();
         assertEquals(asList("one-start", "two-start", "two-stop", "one-stop"), EVENTS);
       }
     }
     

    If dependencies between services can be declared purely via types, consider using the DependsOn annotation instead which is more concise yet equivalent.

    Since:
    1.3
    See Also:
    DependsOn, ServiceDependenciesSpec