Definition
- @Configuration is a specialized @Component that Spring wraps in a CGLIB subclass proxy, enabling inter-bean method references to return existing singletons instead of creating new objects.
- @Bean is a method-level annotation inside @Configuration classes that tells Spring to call the method, take the returned object, and register it as a bean in the application context.
- Full mode is the default behavior of @Configuration where the CGLIB proxy intercepts every @Bean method call, ensuring singleton semantics.
- Lite mode is what happens when you put @Bean methods inside a @Component class instead of a @Configuration class; no proxy is created, so inter-bean calls create new instances.
- CGLIB proxy is a runtime-generated subclass that overrides @Bean methods to check the container first before calling the original method.
Think of National Bank of India setting up a branch office. The branch manager (the @Configuration class) maintains a registry of key resources: the main safe, the security system, the network server. When the loan department asks for the safe, the manager checks the registry and hands over the existing safe. When the savings department also asks for the safe, the manager gives the same one, not a new safe. Without the registry (lite mode), each department gets its own safe, which is wasteful and inconsistent. The CGLIB proxy is the registry that makes this sharing work.
Understanding the Concepts
What is @Configuration?
@Configuration is a class-level annotation that tells Spring: "this class contains @Bean methods that define beans." It is a specialized form of @Component, so the class itself is also registered as a bean. But the key difference is that Spring creates a CGLIB proxy subclass of your @Configuration class.
This proxy intercepts calls to @Bean methods. If a @Bean method has already been called and the bean exists in the container, the proxy returns the existing instance instead of calling the method again.
package com.bank.config;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
class BankConfig {
@Bean
String bankName() {
System.out.println("Creating bankName bean");
return "National Bank of India";
}
}
public class ConfigurationBasicDemo {
public static void main(String[] args) {
var context = new AnnotationConfigApplicationContext(BankConfig.class);
String name1 = context.getBean("bankName", String.class);
String name2 = context.getBean("bankName", String.class);
System.out.println("name1: " + name1);
System.out.println("name2: " + name2);
System.out.println("Same instance: " + (name1 == name2));
System.out.println("Config class: " + context.getBean(BankConfig.class).getClass().getName());
context.close();
}
}
Expected output:
Creating bankName bean
name1: National Bank of India
name2: National Bank of India
Same instance: true
Config class: com.bank.config.BankConfig$$SpringCGLIB$$0
Notice that "Creating bankName bean" prints only once, and the config class name contains $$SpringCGLIB$$, confirming the proxy.
Why does @Configuration exist?
@Configuration exists to solve two problems that @Component cannot:
- Third-party classes: you cannot add @Service to a class from a library like
RestTemplate,ObjectMapper, orHikariDataSource. You need a factory method to create and configure them. - Inter-bean references: when one @Bean method calls another @Bean method, @Configuration's proxy ensures the same singleton is returned. Without the proxy, you get a new instance.
package com.bank.config;
public class WhyConfigurationExists {
public static void main(String[] args) {
System.out.println("Problem 1: Third-party classes");
System.out.println(" Cannot add @Service to RestTemplate (library class)");
System.out.println(" Solution: @Bean RestTemplate restTemplate() { return new RestTemplate(); }");
System.out.println();
System.out.println("Problem 2: Inter-bean references");
System.out.println(" @Bean A a() { return new A(b()); }");
System.out.println(" @Bean B b() { return new B(); }");
System.out.println(" Without @Configuration: a() calls b(), creating a NEW B (not the singleton)");
System.out.println(" With @Configuration: proxy intercepts b() call, returns existing singleton");
}
}
Expected output:
Problem 1: Third-party classes
Cannot add @Service to RestTemplate (library class)
Solution: @Bean RestTemplate restTemplate() { return new RestTemplate(); }
Problem 2: Inter-bean references
@Bean A a() { return new A(b()); }
@Bean B b() { return new B(); }
Without @Configuration: a() calls b(), creating a NEW B (not the singleton)
With @Configuration: proxy intercepts b() call, returns existing singleton
How does full mode (@Configuration) differ from lite mode (@Component with @Bean)?
This is the most important concept to understand. Full mode uses a CGLIB proxy. Lite mode does not.
| Feature | Full Mode (@Configuration) | Lite Mode (@Component with @Bean) |
|---|---|---|
| CGLIB proxy | Yes | No |
| Inter-bean calls return singleton | Yes | No (new instance each call) |
| Performance overhead | Small (proxy creation at startup) | None |
| Use case | Beans that reference each other | Simple independent beans |
| Spring Boot auto-config | Always uses @Configuration | Never |
package com.bank.config;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
// Full mode: CGLIB proxy ensures singleton
@Configuration
class FullModeConfig {
@Bean
StringBuilder auditLog() {
System.out.println(" [Full] Creating auditLog");
return new StringBuilder("AuditLog");
}
@Bean
String auditMessage() {
// Calling auditLog() here returns the SAME instance from the container
return "Message uses: " + auditLog().hashCode();
}
}
// Lite mode: no proxy, new instance every call
@Component
class LiteModeConfig {
@Bean
StringBuilder liteAuditLog() {
System.out.println(" [Lite] Creating liteAuditLog");
return new StringBuilder("LiteAuditLog");
}
@Bean
String liteAuditMessage() {
// Calling liteAuditLog() here creates a NEW instance (bypasses container)
return "Message uses: " + liteAuditLog().hashCode();
}
}
public class FullVsLiteModeDemo {
public static void main(String[] args) {
var context = new AnnotationConfigApplicationContext(
FullModeConfig.class, LiteModeConfig.class);
System.out.println("Full mode:");
var fullLog = context.getBean("auditLog", StringBuilder.class);
var fullMsg = context.getBean("auditMessage", String.class);
System.out.println(" auditLog hash: " + fullLog.hashCode());
System.out.println(" auditMessage: " + fullMsg);
System.out.println(" Same instance: " + fullMsg.contains(String.valueOf(fullLog.hashCode())));
System.out.println();
System.out.println("Lite mode:");
var liteLog = context.getBean("liteAuditLog", StringBuilder.class);
var liteMsg = context.getBean("liteAuditMessage", String.class);
System.out.println(" liteAuditLog hash: " + liteLog.hashCode());
System.out.println(" liteAuditMessage: " + liteMsg);
System.out.println(" Same instance: " + liteMsg.contains(String.valueOf(liteLog.hashCode())));
context.close();
}
}
Expected output:
[Full] Creating auditLog
Full mode:
auditLog hash: 12345678
auditMessage: Message uses: 12345678
Same instance: true
[Lite] Creating liteAuditLog
[Lite] Creating liteAuditLog
Lite mode:
liteAuditLog hash: 87654321
liteAuditMessage: Message uses: 11111111
Same instance: false
In full mode, "Creating auditLog" prints once. In lite mode, "Creating liteAuditLog" prints twice: once for the bean registration, once for the direct method call from liteAuditMessage(). The hash codes are different, proving they are different objects.
What is a complete banking project using @Configuration?
This project uses @Configuration to create and configure third-party clients: a payment gateway client and a fraud check client. These are classes you cannot annotate with @Component because they come from an external library.
Project structure
bank-config-demo/
├── pom.xml
└── src/
├── main/
│ └── java/
│ └── com/
│ └── bank/
│ ├── BankConfigDemoApp.java
│ ├── client/
│ │ ├── PaymentGatewayClient.java
│ │ └── FraudCheckClient.java
│ ├── config/
│ │ └── GatewayConfig.java
│ └── service/
│ └── PaymentService.java
└── test/
└── java/
└── com/
└── bank/
└── config/
└── GatewayConfigTest.java
pom.xml
<?xml version="1.0" encoding="UTF-8"?syn-kw">>
syn-kw"><project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd"syn-kw">>
syn-kw"><modelVersionsyn-kw">>4.0.0syn-kw"></modelVersionsyn-kw">>
syn-kw"><parentsyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-parentsyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>3.4.7syn-kw"></versionsyn-kw">>
syn-kw"></parentsyn-kw">>
syn-kw"><groupIdsyn-kw">>com.banksyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>bank-config-demosyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>1.0.0syn-kw"></versionsyn-kw">>
syn-kw"><propertiessyn-kw">>
syn-kw"><java.versionsyn-kw">>25syn-kw"></java.versionsyn-kw">>
syn-kw"></propertiessyn-kw">>
syn-kw"><dependenciessyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-startersyn-kw"></artifactIdsyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-testsyn-kw"></artifactIdsyn-kw">>
syn-kw"><scopesyn-kw">>testsyn-kw"></scopesyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"></dependenciessyn-kw">>
syn-kw"></projectsyn-kw">>
PaymentGatewayClient.java (simulates third-party class)
package com.bank.client;
import java.math.BigDecimal;
// Simulates a class from a third-party library. No @Component.
public class PaymentGatewayClient {
private final String gatewayUrl;
private final int timeoutMs;
public PaymentGatewayClient(String gatewayUrl, int timeoutMs) {
this.gatewayUrl = gatewayUrl;
this.timeoutMs = timeoutMs;
}
public String charge(String accountId, BigDecimal amount) {
return "Charged " + amount + " INR to " + accountId
+ " via " + gatewayUrl + " (timeout: " + timeoutMs + "ms)";
}
}
FraudCheckClient.java (simulates third-party class)
package com.bank.client;
// Simulates a class from a third-party library. No @Component.
public class FraudCheckClient {
private final String apiUrl;
public FraudCheckClient(String apiUrl) {
this.apiUrl = apiUrl;
}
public String check(String accountId, String amount) {
return "Fraud check passed for " + accountId
+ " (" + amount + " INR) via " + apiUrl;
}
}
GatewayConfig.java
package com.bank.config;
import com.bank.client.FraudCheckClient;
import com.bank.client.PaymentGatewayClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class GatewayConfig {
@Bean
PaymentGatewayClient paymentGatewayClient() {
System.out.println("Creating PaymentGatewayClient bean");
return new PaymentGatewayClient("https://pay.hdfc.com/api", 5000);
}
@Bean
FraudCheckClient fraudCheckClient() {
System.out.println("Creating FraudCheckClient bean");
return new FraudCheckClient("https://fraud.icici.com/check");
}
}
PaymentService.java
package com.bank.service;
import com.bank.client.FraudCheckClient;
import com.bank.client.PaymentGatewayClient;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
@Service
public class PaymentService {
private final PaymentGatewayClient gatewayClient;
private final FraudCheckClient fraudClient;
public PaymentService(PaymentGatewayClient gatewayClient,
FraudCheckClient fraudClient) {
this.gatewayClient = gatewayClient;
this.fraudClient = fraudClient;
}
public String processPayment(String accountId, BigDecimal amount) {
String fraudResult = fraudClient.check(accountId, amount.toPlainString());
System.out.println(fraudResult);
String chargeResult = gatewayClient.charge(accountId, amount);
System.out.println(chargeResult);
return "Payment complete for " + accountId;
}
}
BankConfigDemoApp.java
package com.bank;
import com.bank.service.PaymentService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import java.math.BigDecimal;
@SpringBootApplication
public class BankConfigDemoApp {
public static void main(String[] args) {
SpringApplication.run(BankConfigDemoApp.class, args);
}
@Bean
CommandLineRunner demo(PaymentService paymentService) {
return args -> {
System.out.println("--- Processing payment for Priya ---");
System.out.println(paymentService.processPayment("SAV2001", new BigDecimal("75000.00")));
};
}
}
GatewayConfigTest.java
package com.bank.config;
import com.bank.client.FraudCheckClient;
import com.bank.client.PaymentGatewayClient;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
@SpringBootTest
class GatewayConfigTest {
@Autowired
private PaymentGatewayClient gatewayClient1;
@Autowired
private PaymentGatewayClient gatewayClient2;
@Autowired
private FraudCheckClient fraudClient;
@Test
void beansAreSingletons() {
assertNotNull(gatewayClient1);
assertNotNull(fraudClient);
assertSame(gatewayClient1, gatewayClient2, "Should be same singleton instance");
System.out.println("Test passed: both injections are the same singleton");
}
}
Expected output (application run):
Creating PaymentGatewayClient bean
Creating FraudCheckClient bean
--- Processing payment for Priya ---
Fraud check passed for SAV2001 (75000.00 INR) via https://fraud.icici.com/check
Charged 75000.00 INR to SAV2001 via https://pay.hdfc.com/api (timeout: 5000ms)
Payment complete for SAV2001
How to run
cd bank-config-demo
mvn clean package -DskipTests
java -jar target/bank-config-demo-1.0.0.jar
# Run tests
mvn test
What are common mistakes with @Configuration?
Wrong: using @Component instead of @Configuration for inter-bean references
package com.bank.config;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component // WRONG: lite mode, no CGLIB proxy
public class DataSourceConfigWrong {
@Bean
StringBuilder connectionPool() {
System.out.println("Creating connection pool");
return new StringBuilder("HikariPool");
}
@Bean
String dataSource() {
// This calls connectionPool() directly, creating a NEW StringBuilder
return "DataSource uses pool: " + connectionPool().hashCode();
}
}
Problem: @Component = lite mode. No CGLIB proxy.
connectionPool() is called twice: once for the bean, once from dataSource().
Two different StringBuilder instances are created.
The dataSource bean references a different pool than the one in the container.
Correct: use @Configuration for inter-bean references
package com.bank.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration // CORRECT: full mode, CGLIB proxy intercepts calls
public class DataSourceConfigCorrect {
@Bean
StringBuilder connectionPool() {
System.out.println("Creating connection pool");
return new StringBuilder("HikariPool");
}
@Bean
String dataSource() {
// CGLIB proxy intercepts this, returns the existing singleton
return "DataSource uses pool: " + connectionPool().hashCode();
}
}
Correct: @Configuration = full mode. CGLIB proxy is created.
connectionPool() is called once. The second call from dataSource() returns the existing bean.
Both beans reference the same StringBuilder instance.
Wrong: using proxyBeanMethods = false without understanding the impact
package com.bank.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false) // Disables CGLIB proxy
public class NoBeanProxyConfig {
@Bean
StringBuilder auditLogger() {
System.out.println("Creating auditLogger");
return new StringBuilder("AuditLog");
}
@Bean
String auditService() {
// Without proxy, this creates a NEW StringBuilder, not the singleton
return "AuditService uses: " + auditLogger().hashCode();
}
}
Problem: proxyBeanMethods = false disables the CGLIB proxy.
Behavior is identical to lite mode (@Component).
Inter-bean calls create new instances.
Only use proxyBeanMethods = false when beans are independent and do not call each other.
What about @Configuration with @Profile?
@Configuration works with @Profile to create environment-specific beans. For example, a mock payment gateway in tests and a real one in production.
package com.bank.config;
import com.bank.client.PaymentGatewayClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
public class ProfileBasedConfig {
@Bean
@Profile("prod")
PaymentGatewayClient prodGateway() {
System.out.println("Creating PROD payment gateway");
return new PaymentGatewayClient("https://pay.hdfc.com/api", 5000);
}
@Bean
@Profile("dev")
PaymentGatewayClient devGateway() {
System.out.println("Creating DEV payment gateway (mock)");
return new PaymentGatewayClient("http://localhost:8089/mock-pay", 1000);
}
}
Expected output (spring.profiles.active=dev):
Creating DEV payment gateway (mock)
Expected output (spring.profiles.active=prod):
Creating PROD payment gateway
What should a senior or principal engineer know?
- CGLIB proxy overhead: @Configuration creates a CGLIB subclass at startup. For most applications, this is negligible. But for GraalVM native images, CGLIB is not available. Spring Boot 3.x uses
proxyBeanMethods = falsein its own auto-configuration classes for native image compatibility. - proxyBeanMethods = false: Spring Boot's own auto-configuration classes often use this setting. It means @Bean methods are not proxied, so inter-bean calls create new instances. This is fine when each @Bean method is independent.
- @Configuration vs @AutoConfiguration: in Spring Boot 3.x, auto-configuration classes use @AutoConfiguration instead of @Configuration. @AutoConfiguration adds ordering support (@AutoConfigureBefore, @AutoConfigureAfter) and is registered in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports.
- Bean method visibility: @Bean methods in @Configuration should be non-private and non-final. The CGLIB proxy overrides them, so final methods cannot be proxied.
- Static @Bean methods: if a @Bean method is static, it is called without instantiating the @Configuration class. This is used for BeanFactoryPostProcessor beans that must be created very early in the container lifecycle.
package com.bank.core;
public class SeniorConfigurationKnowledge {
public static void main(String[] args) {
System.out.println("Senior/Principal @Configuration Checklist:");
System.out.println(" 1. @Configuration = CGLIB proxy, full mode");
System.out.println(" 2. proxyBeanMethods=false = no proxy, lite mode");
System.out.println(" 3. Spring Boot auto-configs use proxyBeanMethods=false for native images");
System.out.println(" 4. @Bean methods must not be private or final (proxy cannot override)");
System.out.println(" 5. Static @Bean for BeanFactoryPostProcessor (created before config instance)");
System.out.println(" 6. @AutoConfiguration replaces @Configuration in Boot 3.x auto-configs");
System.out.println(" 7. GraalVM native: CGLIB not available, use proxyBeanMethods=false");
}
}
Expected output:
Senior/Principal @Configuration Checklist:
1. @Configuration = CGLIB proxy, full mode
2. proxyBeanMethods=false = no proxy, lite mode
3. Spring Boot auto-configs use proxyBeanMethods=false for native images
4. @Bean methods must not be private or final (proxy cannot override)
5. Static @Bean for BeanFactoryPostProcessor (created before config instance)
6. @AutoConfiguration replaces @Configuration in Boot 3.x auto-configs
7. GraalVM native: CGLIB not available, use proxyBeanMethods=false
What are common interview follow-up questions?
- What happens if you make a @Bean method final? (The CGLIB proxy cannot override it. In full mode, Spring may throw an error or fall back to lite behavior for that method.)
- Can @Configuration classes be lazy? (Yes. Use @Lazy on the @Configuration class or on individual @Bean methods. Beans are created on first access instead of at startup.)
- What is the difference between @Configuration and @SpringBootConfiguration? (@SpringBootConfiguration is just @Configuration with a marker that tells Spring Boot this is the main configuration class. @SpringBootApplication includes @SpringBootConfiguration.)
- Can you import one @Configuration into another? (Yes. Use @Import(OtherConfig.class) to bring in beans from another @Configuration without component scanning.)
- How do you test @Configuration classes? (Use @SpringBootTest or create an AnnotationConfigApplicationContext with the config class. Verify that expected beans are present and configured correctly.)
- When should you use @Bean over @Component? (When the class is from a third-party library, when you need complex initialization logic, or when the same class needs multiple bean instances with different configurations.)
Visual Overview
@Configuration Full Mode (CGLIB Proxy)
========================================
┌───────────────────────────────────┐
│ @Configuration │
│ GatewayConfig │
│ │
│ @Bean paymentGatewayClient() │
│ @Bean fraudCheckClient() │
└───────────────┬───────────────────┘
│ Spring creates
▼
┌───────────────────────────────────┐
│ GatewayConfig$$SpringCGLIB$$0 │ CGLIB Proxy
│ │
│ paymentGatewayClient() { │
│ if (container has bean) { │
│ return existing singleton; │
│ } │
│ return super.paymentGateway(); │
│ } │
└───────────────────────────────────┘
Full Mode vs Lite Mode
=======================
Full Mode (@Configuration):
┌─────────────────────┐
│ @Bean a() calls b() │
│ │ │
│ ▼ │
│ CGLIB intercepts │
│ │ │
│ ▼ │
│ Returns singleton b │ Same instance
└─────────────────────┘
Lite Mode (@Component with @Bean):
┌─────────────────────┐
│ @Bean a() calls b() │
│ │ │
│ ▼ │
│ Direct method call │
│ │ │
│ ▼ │
│ Creates NEW b │ Different instance!
└─────────────────────┘
Key Takeaway
@Configuration is how you create beans for classes you cannot annotate, like third-party library classes. You write @Bean methods that construct and configure the objects, and Spring registers the returned instances in the application context.
The critical feature of @Configuration is the CGLIB proxy. Spring creates a subclass of your @Configuration class at startup. When one @Bean method calls another, the proxy intercepts the call and returns the existing singleton from the container. Without this proxy (lite mode), each call creates a new object, which breaks singleton semantics.
In our National Bank of India payment project, we used @Configuration to create PaymentGatewayClient and FraudCheckClient beans. These classes came from an external library (simulated), so we could not add @Component to them. The @Configuration class was the only way to register them as beans with the correct constructor arguments.
At the senior level, understand that Spring Boot's own auto-configuration classes use proxyBeanMethods = false for GraalVM native image compatibility. Know that @Bean methods must not be private or final because the CGLIB proxy overrides them. Use static @Bean methods for BeanFactoryPostProcessor beans that need to be created before the @Configuration instance exists.
Remember one sentence: @Configuration creates a CGLIB proxy that makes @Bean method calls return the same singleton, while @Component with @Bean methods does not proxy and creates a new instance on every call.
---