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)
classDiagram
direction LR
class BoxConfig {
<<@Configuration>>
}
class PricingConfig {
<<@Configuration>>
+priceList() PriceList
+membershipService() MembershipService
+dropInService() DropInService
}
class PricingConfig_SpringCGLIB {
<<generated proxy>>
+priceList() returns the cached bean
}
class ClockConfig {
<<@Configuration>>
+systemClock() Clock as boxClock, clock
}
class LitePricingConfig {
<<proxyBeanMethods = false>>
+dropInService(PriceList) DropInService
}
BoxConfig ..> PricingConfig : @Import
BoxConfig ..> ClockConfig : @Import
PricingConfig <|-- PricingConfig_SpringCGLIB : CGLIB subclass
PricingConfig_SpringCGLIB ..> PriceList : one instance
MembershipService --> PriceList
DropInService --> PriceListKey pieces
@Configuration: marks the class as a source of definitions;proxyBeanMethods = trueby default@Bean: the method returns the bean; the name is the method name unless@Bean(name = …)- Parameters of a
@Beanmethod: Spring resolves them as dependencies @Import({A.class, B.class}): composes several configuration classes@Configuration(proxyBeanMethods = false): lite mode, no CGLIB subclassAnnotationConfigApplicationContext(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
@Configurationclass, callingpriceList()from another@Beanmethod returns the container's singleton, not a new object - A generated subclass (
PricingConfig$$SpringCGLIB$$0) that intercepts the@Beanmethods makes that happen - In lite mode (or with
@Beaninside a@Component) a call between methods is a Java call: it creates another object - Asking for the dependency as a parameter of the
@Beanmethod works the same in both modes @Bean(name = {"boxClock", "clock"}): the first is the name, the rest are aliases@Importalso accepts@Componentclasses,ImportSelectorandImportBeanDefinitionRegistrar
Exam traps
- A
@Configurationclass can't befinal(CGLIB needs to subclass it): it fails withBeanDefinitionParsingException @Beanmethods can't beprivateorfinaleither 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@Beanmethod doesn't go through the proxy (it's used forBeanFactoryPostProcessor, see the lifecycle lesson)