Video in progress

How do you compare Java's `ServiceLoader` with Spring Boot auto-configuration for a plugin architecture?

ServiceLoader doesn't depend on any framework and is simple, but it has no DI, conditional loading or ordering. Spring auto-configuration gives you conditions, properties and bean override, but it ties the plugin to Spring.

📖 Answer

Both are based on the same idea: the core declares an interface, the implementation sits in a separate jar on the classpath, and it is discovered through a metadata file.

ServiceLoader:

ServiceLoader.load(ExportFormat.class).stream()
    .map(ServiceLoader.Provider::get)
    .forEach(registry::register);

The implementation is declared in the META-INF/services/com.acme.ExportFormat file or, in JPMS, with provides ... with .... JDBC drivers, java.nio.file.spi, SLF4J 2: all of them work this way. No framework is needed, and the library works without Spring too. But there is no dependency injection into the plugin (a no-args constructor or a static provider() method), and no conditional loading or ordering.

In Spring Boot, the plugin declares its configuration in the META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports file (up to Boot 2.7 this was spring.factories). Then @ConditionalOnClass, @ConditionalOnProperty, @ConditionalOnMissingBean and @AutoConfiguration(after = ...) control when and in what order it turns on. The plugin gets full DI, configuration properties and the lifecycle.

How I choose:

  • if the library must also be usable outside Spring, use ServiceLoader in the core and a thin starter for Spring on top;
  • if all consumers are on Spring Boot, use auto-configuration, because teams expect it anyway;
  • if plugins must be loaded at runtime without a restart, neither is enough: you need separate ClassLoader isolation, and that is another level of complexity.

The most common mistake in auto-configuration is declaring a bean without conditions. Then, when a consumer defines its own bean, two beans collide. Putting @ConditionalOnMissingBean on every bean is nearly a rule.