Interview Prep Zoneby CuriouserLabs

Question 4 of 5 · senior level

@Component vs @Bean vs @Configuration — when do you use each, and what does proxyBeanMethods do?

🎤 Say this first

@Component (+ stereotypes) is for your own classes discovered by scanning. @Bean methods are for wiring third-party or conditionally-built objects where you control construction explicitly. @Configuration classes are CGLIB-enhanced so that @Bean methods calling each other return the same singleton instead of new instances — that's proxyBeanMethods=true. Setting it to false ('lite mode') skips the proxy for faster startup/native-friendliness but silently breaks inter-method call semantics — the subtlest wiring bug in Spring.

The full picture

The proxyBeanMethods trap
@Configuration                       // full mode: CGLIB proxy
class AppConfig {
    @Bean DataSource dataSource() { return buildHikari(); }
    @Bean JdbcTemplate jdbc() {
        return new JdbcTemplate(dataSource());   // ✅ SAME singleton — call intercepted
    }
}

@Configuration(proxyBeanMethods = false)  // lite mode
class LiteConfig {
    @Bean DataSource dataSource() { return buildHikari(); }
    @Bean JdbcTemplate jdbc() {
        return new JdbcTemplate(dataSource());   // ❌ NEW DataSource! plain method call
    }
    // lite done right: declare the dependency as a parameter
    @Bean JdbcTemplate jdbcOk(DataSource ds) { return new JdbcTemplate(ds); }
}
  • Stereotypes are semantic, not cosmetic: @Repository adds exception translation; @Service/@Controller mark architectural roles for humans, AOP pointcuts, and tooling.
  • @Bean also fits: objects needing constructor logic, third-party classes you can't annotate, and definitions that must be conditional (@ConditionalOn… in auto-configurations).
  • Boot's own auto-configurations use proxyBeanMethods=false + parameter injection everywhere — copy that idiom: it's faster and AOT/native-friendly, and parameter injection sidesteps the trap entirely.

🔄 Likely follow-up questions

  • Why do Boot auto-configurations prefer lite mode?
  • How does static @Bean method declaration matter for BFPPs?
  • What breaks if a @Configuration class is final? (CGLIB subclassing)