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.
- In the box
- Two services use the box's price list and there must be only one. See how a @Configuration class guarantees it with a CGLIB proxy, what changes in lite mode, and how @Import splits the configuration.
PricingConfig and PriceList appear in the context, highlighted. A new PriceList() packet travels from the configuration to the bean.
MembershipService and DropInService appear. PricingConfig, highlighted, sends priceList() to each of the two services.
In place of PricingConfig there is its CGLIB proxy, highlighted together with PriceList. The same packets travel from PriceList to each service: both get the same object.
Now LitePricingConfig is there, highlighted. Besides the PriceList bean a copy appears, also highlighted, going to MembershipService; DropInService gets the real bean.
Full view. BoxConfig, highlighted at the top, sends @Import to PricingConfig and ClockConfig. Below, the PriceList, MembershipService, DropInService and boxClock beans.
ClockConfig and the boxClock bean are highlighted. A packet with the names boxClock and clock travels from the configuration to the bean.
FirstConfig and SecondConfig, the latter in red, send "first" and "second" to the same greeting bean, highlighted.
In place of PricingConfig there is a final FinalConfig class, in red with a warning, next to the PriceList bean that never gets created.
Final view: BoxConfig imports PricingConfig and ClockConfig, which create PriceList, MembershipService, DropInService and boxClock inside the context.
Step 1 of 9
One recipe per bean
The box's price list (PriceList) is expensive to build: in real life it would come from a file or the database. In the previous lesson you saw that a @Configuration class describes the beans. Now look at each piece calmly:
@Configurationmarks the class as a source of bean definitions.- Each
@Beanmethod is a recipe: Spring calls it and whatever it returns becomes a bean. - The bean's name is the method name (
priceList) and its type, the return type.
Step 2 of 9
One PriceList or two?
Both services need the list. The most direct way is for their @Bean methods to call priceList().
But wait: in Java, calling a method that does new PriceList() twice creates two objects. If that were the case, the membership and the drop-in would have different lists, and a price update would only reach one of them.
Step 3 of 9
The CGLIB proxy of @Configuration
Spring solves it like this: at startup it does not use your PricingConfig class as is. It generates a CGLIB subclass (PricingConfig$$SpringCGLIB$$0) that overrides every @Bean method:
- If the bean already exists in the container, it returns it.
- If not, it calls your original method, stores the result and returns it.
So priceList() always returns the same object and both services share the list. The test proves it with isSameAs and by looking at the class name.
Step 4 of 9
Lite mode: no proxy
With @Configuration(proxyBeanMethods = false) you tell Spring not to generate the subclass. That's lite mode:
- It starts a bit faster and uses less memory (Spring Boot uses it in all its auto-configurations).
- But a call between
@Beanmethods is plain Java again:membershipService()gets a brand-new copy ofPriceListthat isn't even a bean.
The safe way, in any mode, is to ask for the dependency as a parameter of the method: dropInService(PriceList priceList). Spring resolves the parameter with the container's bean.
Step 5 of 9
Splitting configuration with @Import
A single configuration class for the whole box would grow out of control. The usual thing is to split it by topic and compose it:
PricingConfigwith prices and billing services.ClockConfigwith the box clock.BoxConfig, the entry point, with@Import({PricingConfig.class, ClockConfig.class}).
You start the container with BoxConfig and Spring also processes the imported classes. It doesn't depend on package scanning: the composition is explicit.
Step 6 of 9
Names and aliases
By default the bean name is the method name. You change it with @Bean(name = …):
@Bean("boxClock")gives it another name.@Bean(name = {"boxClock", "clock"}): the first is the name and the rest are aliases. Both lead to the same object.- As soon as you give an explicit name, the method name (
systemClock) no longer exists as a name.
Step 7 of 9
Trap: two beans with the same name
FirstConfig and SecondConfig both define a bean called greeting. What happens?
- In plain Spring Framework, the second definition replaces the first without warning:
greetingis"second". - In Spring Boot, startup fails with
BeanDefinitionOverrideException, becausespring.main.allow-bean-definition-overridingisfalseby default.
Step 8 of 9
Trap: final and private
Because Spring needs to subclass your @Configuration class to create the proxy:
- The class can't be
final: the context doesn't start and the message says the class may not be final. @Beanmethods shouldn't beprivateorfinal: the proxy can't override them.
Step 9 of 9
Recap
@Configuration+@Bean: recipes in Java; bean name = method name.- CGLIB proxy (default): calls between
@Beanmethods return the singleton. - Lite mode (
proxyBeanMethods = falseor@Beanin a@Component): no proxy; ask for dependencies as parameters. @Importcomposes the configuration from one entry point.- Traps:
finalclass, repeated names (Boot fails, Spring overrides).
Code
PricingConfig.java
@Configuration
public class PricingConfig {
@Bean
public PriceList priceList() {
return new PriceList();
}
@Bean
public MembershipService membershipService() {
return new MembershipService(priceList()); // a plain method call…
}
@Bean
public DropInService dropInService() {
return new DropInService(priceList()); // …called twice: one PriceList or two?
}
}PricingConfig.java
@Configuration
public class PricingConfig {
@Bean
public PriceList priceList() {
return new PriceList();
}
@Bean
public MembershipService membershipService() {
return new MembershipService(priceList()); // a plain method call…
}
@Bean
public DropInService dropInService() {
return new DropInService(priceList()); // …called twice: one PriceList or two?
}
}ProxyBeanMethodsTest.java
@Test
void theConfigurationIsAProxyThatReturnsTheSingleton() {
try (var ctx = new AnnotationConfigApplicationContext(PricingConfig.class)) {
PriceList shared = ctx.getBean(PriceList.class);
assertThat(ctx.getBean(MembershipService.class).prices()).isSameAs(shared);
assertThat(ctx.getBean(DropInService.class).prices()).isSameAs(shared);
assertThat(ctx.getBean(PricingConfig.class).getClass().getName())
.contains("$$SpringCGLIB$$"); // a generated subclass of PricingConfig
}
}LitePricingConfig.java
@Configuration(proxyBeanMethods = false) // "lite" mode: no CGLIB subclass
public class LitePricingConfig {
@Bean
public PriceList priceList() {
return new PriceList();
}
@Bean
public MembershipService membershipService() {
return new MembershipService(priceList()); // now really a new PriceList
}
@Bean // the safe way in lite mode: ask for the bean as a parameter
public DropInService dropInService(PriceList priceList) {
return new DropInService(priceList);
}
}BoxConfig.java
@Configuration
@Import({PricingConfig.class, ClockConfig.class}) // compose: one entry point, several focused classes
public class BoxConfig {
}ClockConfig.java
@Configuration
public class ClockConfig {
@Bean(name = {"boxClock", "clock"}) // a name and an alias, instead of the method name
public Clock systemClock() {
return Clock.systemUTC();
}
}OverridingTest.java
@Test
void plainSpringLetsTheLastDefinitionWin() {
try (var ctx = new AnnotationConfigApplicationContext(FirstConfig.class, SecondConfig.class)) {
assertThat(ctx.getBean("greeting")).isEqualTo("second"); // silently replaced
}
}
@Test
void springBootRefusesToOverrideByDefault() {
Throwable error = catchThrowable(() -> new SpringApplicationBuilder(FirstConfig.class, SecondConfig.class)
.web(WebApplicationType.NONE).run().close());
assertThat(Stream.iterate(error, Objects::nonNull, Throwable::getCause))
.anyMatch(BeanDefinitionOverrideException.class::isInstance);
}FinalConfigTest.java
@Configuration
static final class FinalConfig { // CGLIB cannot subclass a final class
@Bean
PriceList priceList() {
return new PriceList();
}
}
@Test
void aFinalConfigurationClassIsRejected() {
assertThatThrownBy(() -> new AnnotationConfigApplicationContext(FinalConfig.class))
.isInstanceOf(BeanDefinitionParsingException.class)
.hasMessageContaining("may not be final");
}BoxConfig.java
@Configuration
@Import({PricingConfig.class, ClockConfig.class}) // compose: one entry point, several focused classes
public class BoxConfig {
}