Overview
ServiceFactory is a utility class that provides static methods for creating and managing Service instances. It handles service instantiation, configuration, and lifecycle management using Java’s ServiceLoader mechanism.
ServiceFactory automatically selects the appropriate service implementation based on the environment (local or OpenShift) and implementation priorities.
Class signature
software.tnb.common.service
Methods
create(Class)
Creates an instance of the specified Service class. If there is only one implementation, it returns that one. Otherwise, it returns a specific implementation for the current environment (local or OpenShift).The Service class to instantiate
An instance of the requested Service class
S- Service type that extendsService<?, ?, ?>
create(Class, Consumer)
Creates a ConfigurableService instance with custom configuration applied via a Consumer.The ConfigurableService class to instantiate
A Consumer that accepts the service configuration and applies custom settings
A configured instance of the requested ConfigurableService
C- Configuration type that extendsServiceConfigurationS- Service type that extendsConfigurableService<?, ?, ?, C>
withService(Class, Consumer)
Creates a Service instance, executes code with it, and handles lifecycle (beforeAll/afterAll) automatically.The Service class to instantiate
A Consumer that accepts the service instance and executes operations
S- Service type that extendsService<?, ?, ?>
withService(Class, Consumer, Consumer)
Creates a ConfigurableService instance with custom configuration, executes code with it, and handles lifecycle automatically.The ConfigurableService class to instantiate
A Consumer that configures the service
A Consumer that executes operations with the service instance
C- Configuration type that extendsServiceConfigurationS- Service type that extendsConfigurableService<?, ?, ?, C>
Service loading mechanism
ServiceFactory uses Java’s ServiceLoader to discover and load service implementations:- Single implementation: If only one implementation exists, it’s returned directly
- Multiple implementations: Services are sorted by priority and filtered by environment
- Environment detection: Automatically selects local or OpenShift implementations
- Concrete classes: Instantiated directly using reflection
For ConfigurableService instances, the factory automatically calls
defaultConfiguration() after instantiation.Error handling
ServiceFactory throwsIllegalArgumentException in the following cases:
- No implementation found for the requested service class
- No enabled implementation found for the current environment
- Failed to instantiate the service class
Related
- Service - Base class for all services
- ConfigurableService - Base class for configurable services
- AccountFactory - Factory for creating Account instances