Week 2 Day 1 — Java Configuration, @Configuration, and @Bean Deep Dive
Goal
Today I want to understand how Spring configuration works with Java code.
Main questions:
- What is Java configuration in Spring?
- What does
@Configurationdo? - What does
@Beando? - What is the difference between
@Componentand@Bean? - Why are
@Configurationclasses special? - What is proxying of
@Configurationclasses? - What is the difference between full and lite configuration mode?
- When should I use
@Bean? - What are common exam traps?
1. Quick Review from Week 1
In Week 1, I learned:
- Spring manages objects called beans.
ApplicationContextis the main Spring container.BeanDefinitionis metadata for creating a bean.- Beans can be registered by component scanning.
- Beans can also be registered with
@Bean. @Componentis used on classes.@Beanis used on methods.
Memory sentence:
@Component is for class-based bean registration.
@Bean is for method-based bean registration.
Today I go deeper into @Configuration and @Bean.
2. What Is Spring Configuration?
Spring configuration tells Spring:
Which objects should be beans, how they should be created, and how they should be connected.
There are several ways to configure Spring:
1. XML configuration
2. Java configuration
3. Annotation-based configuration
4. Auto-configuration in Spring Boot
Modern Spring usually uses:
Java configuration + annotations + Spring Boot auto-configuration
3. What Is Java Configuration?
Java configuration means using Java classes to define Spring beans.
Example:
@Configuration
public class AppConfig {
@Bean
public Clock clock() {
return Clock.systemUTC();
}
}
This class tells Spring:
Create a Clock bean using this method.
The return value of the method becomes a Spring bean.
4. Why Java Configuration Exists
Before annotation-based and Java-based configuration, Spring often used XML.
Example idea:
<bean id="clock" class="java.time.Clock" />
Modern Java configuration is easier because:
- it is type-safe
- it supports refactoring
- it uses normal Java code
- it can contain conditions and logic
- it works well with IDE support
- it avoids large XML files
5. What Is @Configuration?
@Configuration marks a class as a source of bean definitions.
Example:
@Configuration
public class TimeConfig {
@Bean
public Clock clock() {
return Clock.systemUTC();
}
}
Simple definition:
@Configurationtells Spring that this class contains bean definitions.
Exam definition:
@Configurationmarks a class as a configuration class. Spring processes it and registers bean definitions from its@Beanmethods.
6. What Is @Bean?
@Bean marks a method whose return value should become a Spring bean.
Example:
@Bean
public Clock clock() {
return Clock.systemUTC();
}
Spring does this:
1. Calls the clock() method.
2. Takes the returned Clock object.
3. Registers it as a Spring bean.
4. Manages that object inside the ApplicationContext.
Default bean name:
clock
Bean type:
Clock
7. @Bean Method Name and Bean Name
By default, the method name becomes the bean name.
Example:
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
Bean name:
objectMapper
Bean type:
ObjectMapper
8. Custom Bean Name
You can give a custom bean name.
@Bean("customObjectMapper")
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
Bean name:
customObjectMapper
You can also use:
@Bean(name = "customObjectMapper")
or multiple names:
@Bean(name = {"customObjectMapper", "jsonMapper"})
9. When Should I Use @Bean?
Use @Bean when:
- the class comes from a third-party library
- I cannot modify the class
- object creation needs custom logic
- I need to configure constructor arguments manually
- I need to call a factory method
- I need to choose values from properties
- I need to create multiple beans of the same type
Example:
@Configuration
public class TimeConfig {
@Bean
public Clock utcClock() {
return Clock.systemUTC();
}
@Bean
public Clock berlinClock() {
return Clock.system(ZoneId.of("Europe/Berlin"));
}
}
This creates two Clock beans.
10. @Component vs @Bean
This is very important for the exam.
| Topic | @Component | @Bean |
|---|---|---|
| Used on | class | method |
| Object creation | Spring creates the class directly | method creates and returns object |
| Best for | my own classes | third-party/custom objects |
| Discovery | component scanning | configuration class processing |
| Example | TaskService | Clock, ObjectMapper, RestTemplate |
| Custom creation logic | limited | very flexible |
11. Example: Use @Component for Own Class
@Service
public class TaskService {
public void createTask() {
System.out.println("Task created");
}
}
This is my class.
I can annotate it directly.
So @Service / @Component is good.
12. Example: Use @Bean for Third-Party Class
@Configuration
public class JsonConfig {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.findAndRegisterModules();
return mapper;
}
}
ObjectMapper is from Jackson.
I do not own the class.
So I cannot put @Component on it.
@Bean is the right choice.
13. Example: @Bean with Dependencies
A @Bean method can receive other beans as parameters.
Example:
@Configuration
public class ServiceConfig {
@Bean
public TaskService taskService(TaskRepository taskRepository) {
return new TaskService(taskRepository);
}
}
Spring sees that taskService() needs TaskRepository.
So Spring injects the TaskRepository bean into the method.
This is also Dependency Injection.
14. @Bean Method Dependency Flow
Example:
@Configuration
public class AppConfig {
@Bean
public OrderRepository orderRepository() {
return new OrderRepository();
}
@Bean
public OrderService orderService(OrderRepository orderRepository) {
return new OrderService(orderRepository);
}
}
Spring flow:
1. Register BeanDefinition for orderRepository.
2. Register BeanDefinition for orderService.
3. Create OrderRepository bean.
4. Call orderService(orderRepository).
5. Inject OrderRepository into OrderService.
6. Register OrderService as a bean.
15. Direct Method Calls Inside @Configuration
This is a very important exam topic.
Example:
@Configuration
public class AppConfig {
@Bean
public OrderRepository orderRepository() {
return new OrderRepository();
}
@Bean
public OrderService orderService() {
return new OrderService(orderRepository());
}
}
At first glance, it looks like this creates a new OrderRepository manually.
But because the class is annotated with @Configuration, Spring enhances it with a proxy.
So when orderService() calls orderRepository(), Spring returns the managed singleton bean.
Not a new object.
16. Why @Configuration Classes Are Special
@Configuration classes are enhanced by Spring using CGLIB proxying.
That means Spring can intercept calls to @Bean methods.
Example:
orderRepository()
inside the same configuration class does not behave like a normal Java method call.
Spring intercepts it and returns the managed bean from the container.
This preserves singleton behavior.
17. Normal Java Behavior
In normal Java:
public OrderRepository orderRepository() {
return new OrderRepository();
}
public OrderService orderService() {
return new OrderService(orderRepository());
}
Every time I call:
orderRepository()
a new object is created.
18. Spring @Configuration Behavior
With:
@Configuration
Spring enhances the class.
So this:
return new OrderService(orderRepository());
does not necessarily create a new repository each time.
Instead, Spring returns the managed singleton OrderRepository bean.
Memory sentence:
Full
@Configurationclasses proxy@Beanmethods to preserve singleton behavior.
19. Full Configuration Mode
A class annotated with @Configuration runs in full configuration mode.
Example:
@Configuration
public class AppConfig {
@Bean
public A a() {
return new A();
}
@Bean
public B b() {
return new B(a());
}
}
Spring proxies the configuration class.
Calling a() inside b() returns the managed bean.
This protects singleton behavior.
20. Lite Configuration Mode
A class can also have @Bean methods without @Configuration.
Example:
@Component
public class AppConfigLite {
@Bean
public A a() {
return new A();
}
@Bean
public B b() {
return new B(a());
}
}
This can still register beans.
But it is not full configuration mode.
Spring does not proxy the class in the same way.
So calling a() inside b() is a normal Java method call.
That may create a new object.
21. Full vs Lite Configuration
| Topic | Full mode | Lite mode |
|---|---|---|
| Annotation | @Configuration | @Component with @Bean, or other cases |
| Proxy enhanced? | yes | no full enhancement |
| Inter-bean method calls intercepted? | yes | no |
| Singleton preserved in direct method call? | yes | not guaranteed |
| Best for configuration classes | yes | only for simple cases |
Exam memory sentence:
Use
@Configurationfor classes with@Beanmethods, especially when one@Beanmethod calls another.
22. Important: Prefer Method Parameters
Instead of this:
@Bean
public OrderService orderService() {
return new OrderService(orderRepository());
}
Prefer this:
@Bean
public OrderService orderService(OrderRepository orderRepository) {
return new OrderService(orderRepository);
}
Why?
Because dependencies are explicit.
It is also easier to understand and less dependent on internal method-call behavior.
23. @Configuration(proxyBeanMethods = false)
Modern Spring Boot often uses:
@Configuration(proxyBeanMethods = false)
This disables proxying of @Bean methods.
Why?
Performance optimization.
But then direct calls between @Bean methods are not intercepted.
Example:
@Configuration(proxyBeanMethods = false)
public class AppConfig {
@Bean
public A a() {
return new A();
}
@Bean
public B b() {
return new B(a());
}
}
Here, a() inside b() is a normal method call.
It can create a new A, separate from the Spring-managed A bean.
So if proxyBeanMethods = false, prefer method parameter injection:
@Bean
public B b(A a) {
return new B(a);
}
24. @Configuration(proxyBeanMethods = true)
Default behavior:
@Configuration
is basically:
@Configuration(proxyBeanMethods = true)
This means Spring proxies @Bean methods.
It is useful when @Bean methods call each other directly.
25. Exam Trap: proxyBeanMethods
Question:
@Configuration(proxyBeanMethods = false)
public class AppConfig {
@Bean
public A a() {
return new A();
}
@Bean
public B b() {
return new B(a());
}
}
Does b() definitely receive the Spring-managed singleton A bean?
Answer:
No. With proxyBeanMethods = false, Spring does not intercept the direct method call. a() behaves like a normal Java method call inside b(), so it may create a separate A object.
Better:
@Bean
public B b(A a) {
return new B(a);
}
26. @Bean and Scope
By default, beans are singleton.
Example:
@Bean
public Clock clock() {
return Clock.systemUTC();
}
This creates one Clock bean per Spring container.
To change scope:
@Bean
@Scope("prototype")
public MyObject myObject() {
return new MyObject();
}
For now, remember:
Default bean scope is singleton.
27. @Bean and Lifecycle Methods
You can define init and destroy methods.
Example:
@Bean(initMethod = "init", destroyMethod = "cleanup")
public ExternalClient externalClient() {
return new ExternalClient();
}
Example class:
public class ExternalClient {
public void init() {
System.out.println("Connecting...");
}
public void cleanup() {
System.out.println("Disconnecting...");
}
}
Spring calls:
init after bean creation
cleanup when context closes
28. @Bean and @Primary
If multiple beans of the same type exist, one can be primary.
@Configuration
public class ClockConfig {
@Bean
@Primary
public Clock utcClock() {
return Clock.systemUTC();
}
@Bean
public Clock berlinClock() {
return Clock.system(ZoneId.of("Europe/Berlin"));
}
}
If a class needs:
public TimeService(Clock clock) {
}
Spring injects utcClock.
29. @Bean and @Qualifier
Use @Qualifier to select a specific bean.
@Service
public class TimeService {
private final Clock clock;
public TimeService(@Qualifier("berlinClock") Clock clock) {
this.clock = clock;
}
}
This injects:
berlinClock
30. Multiple Beans of Same Type
Example:
@Configuration
public class PaymentConfig {
@Bean
public PaymentProvider stripePaymentProvider() {
return new StripePaymentProvider();
}
@Bean
public PaymentProvider paypalPaymentProvider() {
return new PaypalPaymentProvider();
}
}
If I inject:
public CheckoutService(PaymentProvider paymentProvider) {
}
Spring does not know which one to inject.
Solutions:
1. @Primary
2. @Qualifier
3. Inject List<PaymentProvider>
4. Inject Map<String, PaymentProvider>
5. Use a more specific type
31. @Import
Sometimes I want to import a configuration class explicitly.
Example:
@Configuration
@Import(TimeConfig.class)
public class AppConfig {
}
This registers TimeConfig even if it is not discovered by component scanning.
Useful idea:
@Importbrings another configuration class into the application context.
32. @Configuration and Component Scanning
@Configuration itself is also a Spring stereotype.
So this class can be discovered by component scanning:
@Configuration
public class TimeConfig {
}
If it is inside the scan path, Spring finds it.
Then Spring processes its @Bean methods.
If it is outside the scan path and not imported, Spring will not process it.
33. Real Question: Will This Bean Be Created?
package com.example.config;
@Configuration
public class TimeConfig {
@Bean
public Clock clock() {
return Clock.systemUTC();
}
}
Main class:
package com.example.app;
@SpringBootApplication
public class MyApplication {
}
Will clock be created?
Answer:
Not by default.
Spring Boot scans from:
com.example.app
But TimeConfig is in:
com.example.config
That is not a subpackage of com.example.app.
So TimeConfig is not scanned, and its @Bean method is not processed.
34. How to Fix It
Best fix:
Move main class to root package:
package com.example;
@SpringBootApplication
public class MyApplication {
}
Then Spring scans:
com.example.app
com.example.config
Alternative fix:
@SpringBootApplication(scanBasePackages = "com.example")
public class MyApplication {
}
Or:
@Import(TimeConfig.class)
35. @Bean vs Auto-Configuration
Spring Boot auto-configuration often creates beans for me.
But I can define my own bean to customize behavior.
Example:
Spring Boot may auto-configure an ObjectMapper.
But if I define my own:
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper().findAndRegisterModules();
}
Spring Boot may back off depending on the auto-configuration condition.
This is often based on:
@ConditionalOnMissingBean
Memory sentence:
My custom bean can override or replace Boot’s auto-configured bean when auto-configuration backs off.
36. Real Exam Question: @ConditionalOnMissingBean
Spring Boot auto-configuration often says:
Create this bean only if the user has not already defined one.
This is commonly implemented with:
@ConditionalOnMissingBean
Example idea:
@Bean
@ConditionalOnMissingBean
public SomeService someService() {
return new DefaultSomeService();
}
If I already define my own SomeService, Spring Boot does not create the default one.
37. @Bean for Environment-Specific Configuration
You can combine @Bean with @Profile.
Example:
@Configuration
public class EmailConfig {
@Bean
@Profile("dev")
public EmailSender fakeEmailSender() {
return new FakeEmailSender();
}
@Bean
@Profile("prod")
public EmailSender realEmailSender() {
return new RealEmailSender();
}
}
If profile is dev, Spring creates fakeEmailSender.
If profile is prod, Spring creates realEmailSender.
38. @Bean for Conditional Configuration
You can create beans conditionally.
Example:
@Bean
@ConditionalOnProperty(
name = "feature.audit.enabled",
havingValue = "true"
)
public AuditService auditService() {
return new AuditService();
}
This bean is created only if:
feature.audit.enabled=true
This is more Spring Boot-specific, but useful for understanding auto-configuration.
39. Common Real-World Usage of @Bean
Common things created with @Bean:
Clock
ObjectMapper
RestTemplate
WebClient
PasswordEncoder
SecurityFilterChain
CorsConfigurationSource
CommandLineRunner
ApplicationRunner
DataSource customization
External API clients
Example:
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
This is very common in Spring Security.
40. Real Example: PasswordEncoder
@Configuration
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Then another bean can inject it:
@Service
public class UserService {
private final PasswordEncoder passwordEncoder;
public UserService(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
}
Spring creates the PasswordEncoder bean and injects it into UserService.
41. Real Example: Clock for Testability
Bad:
public class TaskService {
public boolean isOverdue(Task task) {
return task.deadline().isBefore(LocalDate.now());
}
}
This is hard to test because LocalDate.now() depends on real time.
Better:
@Service
public class TaskService {
private final Clock clock;
public TaskService(Clock clock) {
this.clock = clock;
}
public boolean isOverdue(Task task) {
return task.deadline().isBefore(LocalDate.now(clock));
}
}
Config:
@Configuration
public class TimeConfig {
@Bean
public Clock clock() {
return Clock.systemDefaultZone();
}
}
In tests, I can replace Clock with a fixed clock.
This is a very professional use of @Bean.
42. Real Example: External API Client
@Configuration
public class ExternalApiConfig {
@Bean
public TaxApiClient taxApiClient(
@Value("${tax-api.base-url}") String baseUrl
) {
return new TaxApiClient(baseUrl);
}
}
This is useful because the object needs configuration from properties.
43. Exam Trap: @Bean Method Return Type
The declared return type matters for injection.
Example:
@Bean
public PaymentProvider paymentProvider() {
return new StripePaymentProvider();
}
Spring knows this bean as type:
PaymentProvider
and also as the actual implementation type internally.
But for clarity, return the most useful type.
If I need to inject implementation-specific methods, I may return the implementation type:
@Bean
public StripePaymentProvider stripePaymentProvider() {
return new StripePaymentProvider();
}
Best practice:
Return an interface when consumers should depend on abstraction. Return concrete type when specific configuration needs it.
44. Exam Trap: Private @Bean Methods
@Bean methods should not be private.
Spring needs to process them.
Use public or package-private methods normally.
Common style:
@Bean
public Clock clock() {
return Clock.systemUTC();
}
45. Exam Trap: Final @Configuration Class
Because Spring may proxy @Configuration classes using CGLIB, final configuration classes can be problematic when proxying is enabled.
Avoid:
@Configuration
public final class AppConfig {
}
Also avoid final @Bean methods when proxying is needed.
Memory sentence:
Full
@Configurationrelies on proxying, so final classes or methods can break proxy behavior.
46. Exam Trap: Calling @Bean Methods Manually
Outside Spring, calling a @Bean method directly is just a normal Java method call.
Example:
AppConfig config = new final classes or methods can break proxy behavior.
---
## 46. Exam AppConfig();
Clock clock = config.clock();
This object is not necessarily managed by Spring.
To get a Spring-managed bean, use the context:
Clock clock = applicationContext.getBean(Clock.class);
47. Real Exam Question: @Bean
Question:
@Configuration
public class AppConfig {
@Bean
public Clock clock() {
return Clock.systemUTC();
}
}
What is the bean name?
Answer:
The default bean name is:
clock
The method name becomes the bean name.
48. Real Exam Question: @Configuration
Question:
What does @Configuration do?
Answer:
@Configuration marks a class as a source of Spring bean definitions. Spring processes the class and registers beans from its @Bean methods. Full @Configuration classes are also enhanced with proxies so inter-bean method calls can return managed singleton beans.
49. Real Exam Question: @Bean Parameter
Question:
@Bean
public OrderService orderService(OrderRepository registers beans from its `@Bean` methods. Full `@Configuration` classes are also enhanced with proxies so inter-bean method calls can return orderRepository) {
return new OrderService(orderRepository);
}
Where does orderRepository come from?
Answer:
Spring resolves it from the application context. It looks for a bean of type OrderRepository and passes it into the @Bean method.
50. Real Exam Question: Full Configuration
Question:
@Configuration
public class AppConfig {
@Bean
public A a() {
return new A();
}
@Bean
public B b() {
return new B(a());
}
}
Does b() receive the managed singleton A bean?
Answer:
Yes, in full @Configuration mode, Spring proxies the configuration class and intercepts calls to @Bean methods. The call to a() returns the managed singleton bean.
51. Real Exam Question: Lite Configuration
Question:
@Component
public class AppConfig {
@Bean
public A a() {
return new A();
}
@Bean
public B b() {
return new B(a());
}
}
Is the call to a() inside b() intercepted like in full @Configuration?
Answer:
No. This is lite configuration mode. The direct call to a() is a normal Java method call, so it can create a separate object.
52. Real Exam Question: proxyBeanMethods = false
Question:
@Configuration(proxyBeanMethods = false)
public class AppConfig {
@Bean
public A a() {
return new A();
}
@Bean
public B b() {
return new B(a());
}
}
What is the risk?
Answer:
Because proxyBeanMethods = false, Spring does not intercept direct calls between @Bean methods. The call to a() inside b() may create a new A object instead of using the managed singleton A bean.
53. Real Exam Question: Best Style
Question:
Which style is better?
Option A:
@Bean
public B b() {
return new B(a());
}
Option B:
@Bean
public B b(A a) {
return new B(a);
}
Answer:
Option B is usually better because the dependency is explicit and Spring injects the managed A bean as a method parameter. It avoids relying on direct @Bean method calls.
54. Real Exam Question: Config Outside Scan
Question:
If a class with @Configuration is outside component scanning, are its @Bean methods processed?
Answer:
No, not automatically. The configuration class must be registered with Spring, either by component scanning, @Import, or another explicit registration mechanism.
55. Interview Answer
Question:
What is Java configuration in Spring?
Good answer:
Java configuration means defining Spring beans using Java classes and annotations instead of XML.Question:
What is Java configuration in Spring?
Good answer:
Java configuration A class annotated with @Configuration can contain methods annotated with @Bean. Spring processes these methods and registers their return values as beans in the application context. This can contain methods annotated with @Bean. Spring processes these methods and registers approach is type-safe, refactor-friendly, and common in modern Spring applications.
56. Interview Answer
Question:
What is the difference between
@Componentand@Bean?
Good answer:
@Component is used on a class and is discovered through component scanning. It is usually used for my own application classes, such as services or helpers. @Bean is used on a method inside a configuration class, and the return value becomes a Spring bean. @Bean is useful for third-party classes, custom object creation, or when I need more control over how the object is built.
57. Interview Answer
Question:
Why are
@Configurationclasses proxied?
Good answer:
Full @Configuration classes are proxied so Spring can intercept calls to @Bean methods. This preserves singleton behavior when one @Bean method calls another. Without proxying, calling a @Bean method directly would behave like a normal Java method call and could create a new object instead of returning the managed Spring bean.
58. Interview Answer
Question:
What does
@Configuration(proxyBeanMethods = false)mean?
Good answer:
@Configuration(proxyBeanMethods = false) disables proxying of @Bean methods. This can improve startup performance, but it means direct calls between @Bean methods are not intercepted by Spring. Therefore, if one bean depends on another, it is better to use method parameters instead of calling another @Bean method directly.
59. Tiny Code Practice
Create this:
@Configuration
public class TimeConfig {
@Bean
public Clock clock() {
return Clock.systemUTC();
}
}
Then inject it:
@Service
public class DeadlineService {
private final Clock clock;
public DeadlineService(Clock clock) {
this.clock = clock;
}
public LocalDate today() {
return LocalDate.now(clock);
}
}
Question:
Why is this better than calling
LocalDate.now()directly?
Answer:
Because injecting Clock makes the code easier to test. In tests, I can replace the real clock with a fixed clock.
60. Tiny Bug Practice
Problem:
@Configuration(proxyBeanMethods = false)
public class AppConfig {
@Bean
public A a() {
return new A();
}
@Bean
public B b() {
return new B(a());
}
}
Question:
What is the problem?
Answer:
Because proxyBeanMethods = false, the call to a() inside b() is not intercepted. It may create a new A instead of using the Spring-managed A bean.
Better:
@Bean
public B b(A a) {
return new B(a);
}
Practice Questions and Answers
Question 1
What is Java configuration in Spring?
Answer:
Java configuration means defining Spring beans using Java classes and annotations instead of XML. A configuration class can use @Configuration and @Bean methods to register beans.
Question 2
What does @Configuration do?
Answer:
@Configuration marks a class as a source of Spring bean definitions. Spring processes the class and registers beans from its @Bean methods.
Question 3
What does @Bean do?
Answer:
@Bean marks a method whose return value should be registered as a Spring bean.
Question 4
What is the default bean name for this method?
@Bean
public Clock clock() {
return Clock.systemUTC();
}
Answer:
The default bean name is:
clock
The method name becomes the bean name.
Question 5
How can I give a custom bean name?
Answer:
I can give a custom bean name like this:
@Bean("utcClock")
public Clock clock() {
return Clock.systemUTC();
}
Question 6
When should I use @Bean instead of @Component?
Answer:
Use @Bean for third-party classes, classes I cannot modify, custom object creation logic, objects needing properties, factory methods, or multiple beans of the same type.
Question 7
What is the difference between @Component and @Bean?
Answer:
@Component is used on a class and discovered by component scanning. @Bean is used on a method, and the method return value becomes a Spring bean.
Question 8
Can a @Bean method receive dependencies as parameters?
Answer:
Yes. A @Bean method can receive dependencies as method parameters.
Question 9
Where does Spring get the parameter for a @Bean method?
Answer:
Spring resolves the parameter from the application context by finding a matching bean.
Question 10
Why are full @Configuration classes proxied?
Answer:
Full @Configuration classes are proxied so Spring can intercept calls to @Bean methods and return managed singleton beans instead of creating new objects.
Question 11
What happens when one @Bean method calls another inside a full @Configuration class?
Answer:
In full configuration mode, the call is intercepted by Spring and returns the managed bean from the container.
Question 12
Why are full @Configuration classes proxied?
Answer:
Lite configuration mode happens when @Bean methods are declared in a class that is not a full @Configuration class, such as a plain @Component class.
Question 13
What is the risk of lite configuration mode?
Answer:
The risk is that direct calls between @Bean methods are normal Java method calls and may create new objects instead of returning managed singleton beans.
Question 14
What does @Configuration(proxyBeanMethods = false) mean?
Answer:
@Configuration(proxyBeanMethods = false) disables proxying of @Bean methods.
Question 15
What is the risk of proxyBeanMethods = false?
Answer:
The risk is that direct calls between @Bean methods are not intercepted, so they may create separate objects instead of using managed Spring beans.
Question 16
Which style is better and why?
@Bean
public B b() {
return new B(a());
}
or
@Bean
public B b(A a) {
return new B(a);
}
Answer:
This style is usually better:
@Bean
public B b(A a) {
return new B(a);
}
because the dependency is explicit and Spring injects the managed A bean as a method parameter.
Question 17
What must happen for a @Configuration class to be processed?
Answer:
The configuration class must be registered with Spring, usually through component scanning, @Import, or direct registration.
Question 18
What does @Import do?
Answer:
@Import explicitly imports another configuration class into the application context.
Question 19
How can @Bean work together with @Profile?
Answer:
@Bean can be combined with @Profile so that a bean is only created when a specific profile is active.
Question 20
Why is Clock often a good candidate for @Bean?
Answer:
Clock is a good candidate for @Bean because it makes time-based code testable. In production, I can use a real system clock, and in tests, I can@Bean can be combined with @Profile so that a bean is only created when a specific profile is active.
replace it with a fixed clock.
Final Memory Sentences
- Java configuration defines Spring beans with Java code.
@Configurationmarks a class as a source of bean definitions.@Beanmarks a method whose return value becomes a Spring bean.- The default bean name is the
@Beanmethod name. - Use
@Beanfor third-party objects or custom creation logic. @Componentis used on classes.@Beanis used on methods.- A
@Beanmethod can receive dependencies as parameters. - Full
@Configurationclasses are proxied. - Proxying preserves singleton behavior for inter-bean method calls.
- Lite configuration mode does not intercept direct
@Beanmethod calls. @Configuration(proxyBeanMethods = false)disables proxying.- Prefer method parameters over direct calls between
@Beanmethods. - A configuration class must be registered for its
@Beanmethods to be processed. @Importcan explicitly register another configuration class.@Beancan be combined with@Profileor conditions.