Cheatsheet

Java configuration

Key idea

A `@Configuration` class is a bean factory written in Java. Each `@Bean` method is a recipe; Spring calls it once and keeps the result. So that calls between `@Bean` methods respect the singleton, Spring replaces your class with a CGLIB subclass.

Diagram (UML)

ApplicationContextBoxConfigPricingConfigClockConfigMembershipServicePriceList×10DropInServiceboxClock

Key pieces

  • @Configuration: marks the class as a source of definitions; proxyBeanMethods = true by default
  • @Bean: the method returns the bean; the name is the method name unless @Bean(name = …)
  • Parameters of a @Bean method: Spring resolves them as dependencies
  • @Import({A.class, B.class}): composes several configuration classes
  • @Configuration(proxyBeanMethods = false): lite mode, no CGLIB subclass
  • AnnotationConfigApplicationContext(BoxConfig.class): starts from one or more configuration classes

BoxConfig.java

@Configuration
@Import({PricingConfig.class, ClockConfig.class}) // compose: one entry point, several focused classes
public class BoxConfig {
}

Remember for the exam

  • In a regular @Configuration class, calling priceList() from another @Bean method returns the container's singleton, not a new object
  • A generated subclass (PricingConfig$$SpringCGLIB$$0) that intercepts the @Bean methods makes that happen
  • In lite mode (or with @Bean inside a @Component) a call between methods is a Java call: it creates another object
  • Asking for the dependency as a parameter of the @Bean method works the same in both modes
  • @Bean(name = {"boxClock", "clock"}): the first is the name, the rest are aliases
  • @Import also accepts @Component classes, ImportSelector and ImportBeanDefinitionRegistrar

Exam traps

  • A @Configuration class can't be final (CGLIB needs to subclass it): it fails with BeanDefinitionParsingException
  • @Bean methods can't be private or final either if you want the proxy to intercept them
  • Two beans with the same name: plain Spring lets the last one win silently; Spring Boot fails at startup with BeanDefinitionOverrideException
  • A static @Bean method doesn't go through the proxy (it's used for BeanFactoryPostProcessor, see the lifecycle lesson)

← Java configuration · Run it