Skip to content

Commit

Permalink
[ServiceFactory] Add withService method for one-off usecases
Browse files Browse the repository at this point in the history
  • Loading branch information
avano authored and mmuzikar committed Jan 25, 2023
1 parent 5585cde commit a7cd8d0
Showing 1 changed file with 18 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

import java.util.Optional;
import java.util.ServiceLoader;
import java.util.function.Consumer;
import java.util.stream.StreamSupport;

public final class ServiceFactory {
Expand Down Expand Up @@ -63,4 +64,21 @@ public static <S extends Service> S create(Class<S> clazz) {
.getOrThrow((e) -> new IllegalArgumentException("Failed to instantiate class " + clazz.getSimpleName(), e));
}
}

public static <S extends Service> void withService(Class<S> clazz, Consumer<S> code) {
S service = create(clazz);
try {
service.beforeAll(null);
} catch (Exception e) {
throw new RuntimeException(e);
}

code.accept(service);

try {
service.afterAll(null);
} catch (Exception e) {
LOG.warn("Exception thrown while undeploying service", e);
}
}
}

0 comments on commit a7cd8d0

Please sign in to comment.