Package com.oorian.inject
Class ServiceRegistry
java.lang.Object
com.oorian.inject.ServiceRegistry
- All Implemented Interfaces:
ServiceLocator
Lightweight, built-in service container for projects not using Spring or CDI.
Supports two registration modes:
- Singleton — register a pre-created instance, returned on every lookup
- Factory — register a
Supplier, called on each lookup to create a new instance
Usage:
// In Application.initialize()
ServiceRegistry registry = new ServiceRegistry();
// Singleton registration
registry.register(UserService.class, new UserServiceImpl(dataSource));
registry.register(EmailService.class, new SmtpEmailService(config));
// Factory registration (new instance per lookup)
registry.registerFactory(ReportGenerator.class, () -> new ReportGenerator());
// Activate as the service locator
Services.setServiceLocator(registry);
Thread-safe. All operations use ConcurrentHashMap.
- Since:
- 2.1
- Version:
- 1.0
- Author:
- Marvin P. Warble Jr.
- See Also:
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionclear()Removes all service registrations.<T> TResolves a service by its type.<T> booleanChecks whether a service is available for the given type.<T> ServiceRegistryRegisters a singleton service instance.<T> ServiceRegistryregisterFactory(Class<T> serviceClass, Supplier<T> factory) Registers a factory that creates a new instance on each lookup.unregister(Class<?> serviceClass) Removes a service registration.
-
Constructor Details
-
ServiceRegistry
public ServiceRegistry()Creates an empty service registry.
-
-
Method Details
-
register
Registers a singleton service instance.The same instance is returned for every
get(Class)call.- Type Parameters:
T- the service type- Parameters:
serviceClass- the service class or interfaceinstance- the service instance- Returns:
- this registry for method chaining
-
registerFactory
Registers a factory that creates a new instance on each lookup.- Type Parameters:
T- the service type- Parameters:
serviceClass- the service class or interfacefactory- the supplier that creates service instances- Returns:
- this registry for method chaining
-
unregister
Removes a service registration.- Parameters:
serviceClass- the service class to unregister- Returns:
- this registry for method chaining
-
clear
Removes all service registrations.- Returns:
- this registry for method chaining
-
get
Description copied from interface:ServiceLocatorResolves a service by its type.- Specified by:
getin interfaceServiceLocator- Type Parameters:
T- the service type- Parameters:
serviceClass- the service class or interface- Returns:
- the service instance
-
has
Description copied from interface:ServiceLocatorChecks whether a service is available for the given type.- Specified by:
hasin interfaceServiceLocator- Type Parameters:
T- the service type- Parameters:
serviceClass- the service class or interface- Returns:
trueif a service is registered for the type
-