Sobes.tech
Senior

How would you implement your IoC container? How is the ApplicationContext structured?

sobes.tech AI

Answer from AI

IoC container (Inversion of Control) is a mechanism that manages the creation and binding of objects, reversing control over dependencies from code to the container.

To implement a simple IoC container, you can:

  • Create a registry (for example, Map<Class, Provider>), where the key is an interface or class, and the value is a factory or instance.
  • When requesting an object, the container creates or returns an already created instance, resolving dependencies through constructors or setters.
  • Support scopes (singleton, prototype).

An example of a simplified implementation in Java:

public class SimpleIoC {
    private Map<Class<?>, Supplier<?>> providers = new HashMap<>();

    public <T> void register(Class<T> iface, Supplier<T> provider) {
        providers.put(iface, provider);
    }

    public <T> T resolve(Class<T> iface) {
        Supplier<?> provider = providers.get(iface);
        if (provider == null) {
            throw new RuntimeException("No provider registered for " + iface);
        }
        return iface.cast(provider.get());
    }
}

ApplicationContext in Spring is an extended IoC container that:

  • Loads configuration from XML, annotations, or Java configuration.
  • Manages the lifecycle of beans (creation, initialization, destruction).
  • Supports various scopes (singleton, prototype, request, etc.).
  • Allows dependency injection through constructors, fields, methods.
  • Provides events and listeners.
  • Integrates with other Spring modules.

Thus, ApplicationContext is a powerful container that extends the basic IoC, adding functionality for managing configuration and the lifecycle of components.