0 day streak
java / intermediate
Snippet

Deferred Initialization using @Lazy

The @Lazy annotation prevents Spring from creating a bean at startup. Instead, it is initialized only when it is first requested, which can speed up application startup.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
@Service
public class ReportService {
@Lazy
@Autowired
private HeavyEmailClient emailClient;
public void send() {
emailClient.dispatch();
}
}
spring
Breakdown
1
@Lazy
Indicates whether a bean is to be lazily initialized.
2
@Autowired
Spring injects a proxy instead of the real bean until the first method call occurs.