Jakarta annotations and the Spring bean lifecycle
Trace Spring bean initialization and destruction across Jakarta annotations, Spring callbacks, and bean methods, then compare Resource and Autowired.
A bean can use Jakarta
@PostConstructand@PreDestroyalongside Spring lifecycle interfaces and custom callbacks. I use the callback order to decide where startup work belongs and which dependencies can safely be called.
The examples use Spring Boot 3.4 and Jakarta Annotations 2.1. The baseline Boot starter provides the Jakarta Annotations API.
The Jakarta annotations Spring recognizes
JSR 250 consolidated annotations used across the Java platform. The current API is Jakarta Annotations, under jakarta.annotation. Three annotations show up often in Spring applications. @PostConstruct runs an initialization method after injection. @PreDestroy runs cleanup before the container disposes of a managed bean. @Resource lets a class inject a dependency by name.
Spring’s CommonAnnotationBeanPostProcessor detects these annotations. It participates in both bean initialization and destruction. This matters when a bean declares both a standard annotation and a Spring callback, because they enter the same lifecycle through different hooks.
The callback order for a singleton bean
Spring supports annotated lifecycle methods, the InitializingBean and DisposableBean interfaces, and the initMethod and destroyMethod attributes on a bean definition. With distinct methods declared through all three mechanisms, initialization starts with @PostConstruct, then afterPropertiesSet(), then the configured init method. On shutdown, Spring runs @PreDestroy, DisposableBean.destroy(), and then the configured destroy method.
flowchart TD
CREATE["Create bean and inject dependencies"] --> POST["@PostConstruct"]
POST --> INIT["afterPropertiesSet and custom init"]
INIT --> READY["Use bean"]
READY -->|"Close context"| PRE["@PreDestroy"]
PRE --> DESTROY["DisposableBean and custom destroy"]
This sample logs each callback, including the constructor. Register the bean, start the application, then close the context gracefully. The constructor and initialization messages appear at startup. The three destruction messages appear during the shutdown.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// src/main/java/com/example/lifecycle/LifecycleDemoBean.java
package com.example.lifecycle;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class LifecycleDemoBean implements InitializingBean, DisposableBean {
private static final Logger log = LoggerFactory.getLogger(LifecycleDemoBean.class);
public LifecycleDemoBean() {
log.info("[1] Constructor called");
}
@PostConstruct
public void postConstruct() {
log.info("[2] Run @PostConstruct");
}
@Override
public void afterPropertiesSet() {
log.info("[3] Run InitializingBean.afterPropertiesSet()");
}
public void customInit() {
log.info("[4] Run the configured init method");
}
@PreDestroy
public void preDestroy() {
log.info("[5] Run @PreDestroy");
}
@Override
public void destroy() {
log.info("[6] Run DisposableBean.destroy()");
}
public void customDestroy() {
log.info("[7] Run the configured destroy method");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// src/main/java/com/example/lifecycle/LifecycleConfig.java
package com.example.lifecycle;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class LifecycleConfig {
@Bean(initMethod = "customInit", destroyMethod = "customDestroy")
public LifecycleDemoBean lifecycleDemoBean() {
return new LifecycleDemoBean();
}
}
Compare the marker numbers in the application logs with the callback order above. When one of the lines is missing, check whether Spring owns the bean and whether the context actually closed. Calling new LifecycleDemoBean() outside Spring exercises the constructor alone.
When initialization needs transactions or proxies
@PostConstruct is useful for checking injected configuration, building local data structures, and opening resources owned by the bean. It runs during initialization, before the bean’s normal AOP proxy is available to callers. A method marked @Transactional does not start a transaction just because another method calls it on the same instance.
For database-backed cache warmup, this example listens for Boot’s ApplicationReadyEvent. The container has already initialized its beans and created the relevant proxies. In a real warmup, choose whether startup should wait for the work and what the application should do if that work fails.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// src/main/java/com/example/lifecycle/CacheWarmupListener.java
package com.example.lifecycle;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component
public class CacheWarmupListener {
// Run after bean initialization and proxy creation
@EventListener(ApplicationReadyEvent.class)
@Transactional(readOnly = true)
public void warmupCache() {
// Load the initial cache entries from the database
}
}
Spring initializes prototype beans, including their
@PostConstructmethods. It hands the instances to the caller and does not manage their destruction. A prototype that owns a resource needs an explicit cleanup strategy.
Name-based lookup and type-based lookup
@Resource resolves an explicit name as a bean name. If you omit it, Spring can infer a name from the field or setter and fall back to a type lookup when that inferred name is absent. @Autowired starts with compatible types. Qualifiers narrow the candidates, and a primary bean or name match can help resolve remaining ambiguity under Spring’s rules.
flowchart TD
R1["@Resource reads the bean name"] --> R2{"Matching name?"}
R2 -->|"Yes"| R3["Inject the named bean"]
R2 -->|"Missing inferred name"| R4["Try lookup by type"]
A1["@Autowired reads the type"] --> A2["Narrow compatible candidates"]
| Question | Jakarta @Resource | Spring @Autowired |
|---|---|---|
| Where can I put it? | Field or setter | Constructor, field, or method |
| How does lookup start? | Explicit or inferred name | Candidate type |
| Which processor reads it? | CommonAnnotationBeanPostProcessor | AutowiredAnnotationBeanPostProcessor |
| How do I make it optional? | No annotation-level switch | required = false or an optional declaration |
The sample has email and SMS senders. It identifies the SMS sender by name and passes the email sender through a qualified constructor parameter.
1
2
3
4
5
6
// src/main/java/com/example/resource/NotificationSender.java
package com.example.resource;
public interface NotificationSender {
void send(String target, String message);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// src/main/java/com/example/resource/NotificationSenders.java
package com.example.resource;
import org.springframework.stereotype.Component;
@Component("emailSender")
class EmailSender implements NotificationSender {
@Override
public void send(String target, String message) {
// Send email
}
}
@Component("smsSender")
class SmsSender implements NotificationSender {
@Override
public void send(String target, String message) {
// Send an SMS
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// src/main/java/com/example/resource/AlertService.java
package com.example.resource;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class AlertService {
// 1. @Resource resolves the explicit smsSender bean name
@Resource(name = "smsSender")
private NotificationSender smsSender;
// 2. Qualified constructor injection supports final fields and plain unit tests
private final NotificationSender emailSender;
public AlertService(@Qualifier("emailSender") NotificationSender emailSender) {
this.emailSender = emailSender;
}
public void alertAll(String target, String message) {
emailSender.send(target, message);
smsSender.send(target, message);
}
}
Choosing where to put lifecycle work
I use constructor injection with a qualifier when a required dependency has multiple implementations. It keeps the field final and allows direct construction in a unit test. I reserve lifecycle callbacks for work tied to the lifetime of the bean. When startup work requires AOP advice, I put it behind a Spring-managed call that runs after initialization. To verify the design, start the context, exercise the real proxy, and close it to check the resource cleanup path.