Class ServiceRegistry

java.lang.Object
io.github.connellite.container.ServiceRegistry

public final class ServiceRegistry extends Object
Dynamic registry of application services. The global singleton is available via getInstance(); isolated registries can be created with create().

For an interface type, get(Class) returns a lazy proxy that resolves the current registration on every method call. The proxy can be obtained before register(Class, Object); resolution fails at first use with ServiceNotRegisteredException if nothing is registered yet. A later register makes subsequent invocations succeed; replacing a registration is visible on the next call (OSGi-style dynamic lookup).

For a concrete class, get looks up the registered instance immediately and throws ServiceNotRegisteredException when the type is missing.

  • Constructor Details

    • ServiceRegistry

      public ServiceRegistry()
  • Method Details

    • getInstance

      public static ServiceRegistry getInstance()
    • create

      public static ServiceRegistry create()
      Creates a new isolated registry that does not share state with getInstance().
    • register

      public <T> void register(Class<T> type, T instance)
      Registers instance under type. Replaces any previous registration for the same type.
      Throws:
      IllegalArgumentException - if instance is not an instance of type
    • registerIfAbsent

      public <T> boolean registerIfAbsent(Class<T> type, T instance)
      Registers instance only when type is not registered yet.
      Returns:
      true if registered, false if type was already present
      Throws:
      IllegalArgumentException - if instance is not an instance of type
    • unregister

      public <T> T unregister(Class<T> type)
      Removes the registration for type, if any.
      Returns:
      the previous instance, or null if none was registered
    • get

      public <T> T get(Class<T> type)
      Returns a lazy proxy for an interface type, or the registered instance for a concrete type.
    • contains

      public boolean contains(Class<?> type)
    • clear

      public void clear()
      Removes all registrations and cached lazy proxies in this registry.