Spring / Spring7 Intermediate to Advanced Interview questions
How does Spring Framework 7's BeanRegistrar differ from a traditional @Configuration class with multiple @Bean methods?
A @Configuration class with several @Bean methods is fundamentally declarative: each method runs and produces exactly one bean, unconditionally, unless individually decorated with @Conditional-family annotations - registering a variable number of beans, or beans whose type or name depends on runtime data, quickly turns into a stack of conditional annotations that gets hard to follow.
// @Bean approach - one bean per method, conditions bolted on @Bean @ConditionalOnProperty("feature.metrics.enabled") public MeterRegistry meterRegistry() { return new SimpleMeterRegistry(); } // BeanRegistrar approach - imperative, can loop and branch freely class FeatureBeansRegistrar implements BeanRegistrar { public void register(BeanRegistry registry, Environment env) { if (env.getProperty("feature.metrics.enabled", Boolean.class, false)) { registry.registerBean("meterRegistry", MeterRegistry.class, spec -> spec.supplier(ctx -> new SimpleMeterRegistry())); } } }
BeanRegistrar flips that model to imperative: a single register() method receives a BeanRegistry and the Environment directly, so it can use ordinary Java control flow - loops, conditionals, computed bean names - to register however many beans of whatever types the runtime situation calls for, all in one place rather than scattered across many separately-conditioned methods. The trade-off is readability at a glance: a page of @Bean methods is easy to skim and see every bean the configuration produces, while a BeanRegistrar's output depends on running its logic mentally (or in a debugger). That's why it's best reserved for genuinely dynamic registration scenarios - often framework or library code - rather than replacing straightforward, static @Bean methods across the board.
More Related questions...