Video in progress
What patterns are Spring's extension mechanisms (BeanPostProcessor, BeanFactoryPostProcessor, ImportSelector) built on, and what do you learn from them when designing your own framework?
The Spring container gives hooks at specific points in the lifecycle: changing bean definitions (BeanFactoryPostProcessor), wrapping or replacing a finished bean (BeanPostProcessor), and conditionally loading configuration (ImportSelector). The main lesson is that the core stays small and features are added through these hooks.
📖 Answer
Most of Spring's own features aren't written into the core; they are added through extension points:
@Transactional,@Async,@Cacheable:AbstractAutoProxyCreator(a BeanPostProcessor) replaces the bean with a proxy. Decorator + proxy;@Valueand${...}placeholders:PropertySourcesPlaceholderConfigurer(a BeanFactoryPostProcessor) works on the bean definitions;- reading
@Configurationclasses:ConfigurationClassPostProcessor, which is also a BeanFactoryPostProcessor; @EnableXxxannotations: extra configuration through@ImportandImportSelector/ImportBeanDefinitionRegistrar;ApplicationListeneris an observer, andAwareinterfaces are callback injection.
The lifecycle is roughly: definitions are collected → BeanFactoryPostProcessors modify them → beans are created → BeanPostProcessors wrap them in before/afterInitialization. The contract of each stage is clear: a BeanFactoryPostProcessor must not create bean objects, otherwise they skip the later post-processing and you get the warning "Bean X is not eligible for getting processed by all BeanPostProcessors". If you see this warning on prod, it often means some bean's proxy wasn't created, for example @Transactional isn't working.
Lessons to carry into your own internal framework:
- Separate the stages clearly. "Reading configuration", "creating objects" and "decorating objects" each get their own hook. A single universal
onEventhook makes everything possible and guarantees nothing. - Order is part of the contract. Spring makes this explicit with
Ordered/PriorityOrdered. Your hooks should declare their order too. - Write down what you must not do inside a hook, and check it at runtime if you can.
- Opt-in. The
@EnableXxxstyle: a capability turns on only when requested. Unexpected behavior shouldn't appear just because a library is on the classpath.
One more lesson is AOT. For native images, Spring 6 had to move these dynamic mechanisms to build time. If your framework relies heavily on runtime reflection, expect to run into the same kind of limit later.
Sign up to mark studied questions and save your progress.