Configuration Classes & @Bean
Component scanning only works for classes you wrote and can annotate. To register an object from a library — a Clock, an ObjectMapper, an HTTP client, a password encoder — or to build a bean with custom logic, you write a @Configuration class with @Bean methods. Each method's return value becomes a bean, and the method name becomes the bean name.
A first configuration class
package com.example.tasks.config;
import java.time.Clock;
import java.time.ZoneId;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
Clock clock() {
return Clock.system(ZoneId.of("Asia/Ho_Chi_Minh"));
}
@Bean
DueDateCalculator dueDateCalculator(Clock clock) { // parameters are injected
return new DueDateCalculator(clock, 7);
}
}@Bean methods can declare parameters: Spring resolves them from the context exactly like constructor parameters. Any class can now ask for a Clock in its constructor.
Tip: Injecting a
Clockbean instead of callingLocalDate.now()directly makes time-dependent code testable: tests pass aClock.fixed(...).
That tip, in runnable form — the same calculator gives predictable results with a fixed clock:
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
class DueDateCalculator {
private final Clock clock;
private final int defaultDays;
DueDateCalculator(Clock clock, int defaultDays) {
this.clock = clock;
this.defaultDays = defaultDays;
}
LocalDate dueDate() {
return LocalDate.now(clock).plusDays(defaultDays);
}
boolean isOverdue(LocalDate due) {
return due.isBefore(LocalDate.now(clock));
}
}
class Main {
public static void main(String[] args) {
Clock fixed = Clock.fixed(Instant.parse("2025-03-28T10:00:00Z"), ZoneOffset.UTC);
DueDateCalculator calc = new DueDateCalculator(fixed, 7);
System.out.println("Due: " + calc.dueDate());
System.out.println("Overdue 2025-03-27? " + calc.isOverdue(LocalDate.of(2025, 3, 27)));
System.out.println("Overdue 2025-03-28? " + calc.isOverdue(LocalDate.of(2025, 3, 28)));
}
}Due: 2025-04-04
Overdue 2025-03-27? true
Overdue 2025-03-28? false
@Bean vs. @Component
@Component on a class |
@Bean method |
|
|---|---|---|
| Where | on your own class | in a @Configuration class |
| Works for library classes | no | yes |
| Construction logic | constructor only | any Java code |
| Several beans of one type | one per class | as many methods as you like |
| Bean name | decapitalised class name | method name (or @Bean("name")) |
Why @Configuration classes are special
In a @Configuration class, Spring wraps the class in a CGLIB subclass. When one @Bean method calls another, the call is intercepted and the existing singleton is returned instead of creating a new object:
@Configuration
class DataConfig {
@Bean DataSource dataSource() { return new HikariDataSource(); }
@Bean JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource()); // returns the singleton, not a new pool
}
}This plain-Java program imitates the generated subclass by overriding the method and caching its result:
import java.util.HashMap;
import java.util.Map;
class Pool {
private static int count = 0;
final int id = ++count;
}
class DataConfig {
Pool dataSource() { return new Pool(); }
String jdbcTemplate() { return "JdbcTemplate using pool #" + dataSource().id; }
String reportJob() { return "ReportJob using pool #" + dataSource().id; }
}
// What Spring generates for a @Configuration class (simplified)
class DataConfigProxy extends DataConfig {
private final Map<String, Object> singletons = new HashMap<>();
@Override
Pool dataSource() {
return (Pool) singletons.computeIfAbsent("dataSource", k -> super.dataSource());
}
}
class Main {
public static void main(String[] args) {
DataConfig plain = new DataConfig();
System.out.println("Without proxy:");
System.out.println(" " + plain.jdbcTemplate());
System.out.println(" " + plain.reportJob());
DataConfig proxied = new DataConfigProxy();
System.out.println("With proxy:");
System.out.println(" " + proxied.jdbcTemplate());
System.out.println(" " + proxied.reportJob());
}
}Without proxy:
JdbcTemplate using pool #1
ReportJob using pool #2
With proxy:
JdbcTemplate using pool #3
ReportJob using pool #3
Without the proxy, each call builds a brand-new pool — exactly the bug that "lite mode" (@Configuration(proxyBeanMethods = false), or @Bean methods in a plain @Component) can cause. With lite mode, prefer method parameters to pass beans around, which is always safe.
Note: Spring Boot's own auto-configuration classes use
proxyBeanMethods = falsefor faster startup, and they always pass dependencies as parameters.
Conditional and named beans
@Configuration
class NotificationConfig {
@Bean
@ConditionalOnProperty(name = "notifications.mode", havingValue = "email")
Notifier emailNotifier() { return new EmailNotifier(); }
@Bean
@ConditionalOnMissingBean(Notifier.class)
Notifier logNotifier() { return new LogNotifier(); }
}With notifications.mode=email the email notifier is created; otherwise the fallback log notifier fills the gap. These conditions are the building blocks of auto-configuration, covered in the next lesson.
Initialisation and destruction hooks can also be declared on the @Bean itself — handy for library classes you cannot annotate:
@Bean(initMethod = "start", destroyMethod = "shutdown")
LegacyScheduler scheduler() { return new LegacyScheduler(); }curl -s localhost:8080/actuator/beans | jq '.contexts.tasks.beans.clock'{
"aliases": [],
"scope": "singleton",
"type": "java.time.Clock$ZoneClock",
"resource": "class path resource [com/example/tasks/config/AppConfig.class]",
"dependencies": [
"appConfig"
]
}
The Actuator beans endpoint (when exposed) shows where each bean came from — useful for answering "who created this?".
Test yourself
When must you use a @Bean method instead of @Component?
- For every service
- To register an instance of a library class you cannot annotate
- For controllers
- Never; they are equivalent
What is the bean name produced by @Bean Clock systemClock() { ... }?
clockClocksystemClockappConfig.clock
In a proxied @Configuration class, what does calling dataSource() from another @Bean method return?
- A new DataSource each time
- The singleton DataSource bean
- null
- A compile error