The 30 second answer
SpringFactoriesLoader is Spring Framework's mechanism for discovering and creating extension implementations registered by libraries. It loads the implementations for a requested interface and sorts them using Spring's ordering rules, including @Order. Spring Boot uses it for startup listeners, context initializers, property loaders and logging extensions, including components needed before the application context exists. Since Spring Boot 3, auto-configuration discovery is separate; that goes through AutoConfigurationImportSelector instead.
spring.factories is a properties file that maps an interface name to a list of implementation names:
org.springframework.boot.env.PropertySourceLoader=\
org.springframework.boot.env.PropertiesPropertySourceLoader,\
org.springframework.boot.env.YamlPropertySourceLoaderspring-boot/META-INF/spring.factories L8-L10
The loader's core method reads names, creates instances and sorts them:
List<String> implementationNames = loadFactoryNames(factoryType);
List<T> result = new ArrayList<>(implementationNames.size());
for (String implementationName : implementationNames) {
T factory = instantiateFactory(implementationName, factoryType, argumentResolver, failureHandlerToUse);
if (factory != null) {
result.add(factory);
}
}
AnnotationAwareOrderComparator.sort(result);
return result;SpringFactoriesLoader.java L192-L208, with the default location META-INF/spring.factories at L98.
Where Spring Boot uses it. In the SpringApplication constructor:
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));SpringApplication.java L268-L270, and getSpringFactoriesInstances delegates to SpringFactoriesLoader.forDefaultResourceLocation(...) (L459-L461). These extensions must exist before the application context, so they cannot be normal beans. That is the real reason this mechanism exists.
History worth knowing:
- Up to Spring Boot 2.6, auto-configurations were listed under the
EnableAutoConfigurationkey inspring.factories. - Spring Boot 2.7 introduced
META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.importsand the@AutoConfigurationannotation. - Spring Boot 3.0 removed support for registering auto-configurations in
spring.factories.
Interview trap: "auto-configuration is loaded through spring.factories" is outdated for Spring Boot 3 and 4. A good answer separates the two files: spring.factories for early framework extensions, .imports for auto-configuration candidates.
Sources (3)
- SpringFactoriesLoader Javadocdocs.spring.io
- Spring Boot 2.7 release notes: new auto-configuration registrationgithub.com
- Spring Boot 3.0 migration guidegithub.com