Spring AOT (Ahead-of-Time) — phân tích config app lúc build time thay vì runtime.
Khác biệt:
| Runtime DI (truyền thống) | AOT | |
|---|---|---|
| Resolve bean | Lúc startup, qua reflection + classpath scanning | Build time, sinh Java code |
| Startup | 4+ giây | <100ms (với Native Image) |
| Memory | Cao | Thấp |
| GraalVM Native | Khó | Hỗ trợ tốt |
Cơ chế AOT:
1. Maven/Gradle plugin chạy process-aot goal.
2. Phân tích @Configuration, @Component, bean dependency.
3. Sinh ra Java code thuần (không reflection): bean definition, proxy class, reflection hint.
4. Code này compile chung với app code.
mvn spring-boot:process-aot # sinh AOT code
mvn -Pnative native:compile # build native imageRàng buộc:
- Không thể đăng ký bean động runtime (BeanDefinitionRegistryPostProcessor hạn chế).
- Reflection cần khai báo hint (@RegisterReflectionForBinding).
- Conditional bean (@ConditionalOnProperty) resolve lúc build, không phải runtime.
Khi dùng: kết hợp với GraalVM Native Image cho serverless (Lambda), CLI tool, microservice cần scale-to-zero nhanh.
Spring AOT (Ahead-of-Time) — analyses app configuration at build time instead of runtime.
Differences:
| Runtime DI (traditional) | AOT | |
|---|---|---|
| Bean resolution | At startup, via reflection + classpath scanning | Build time, generates Java code |
| Startup | 4+ seconds | <100ms (with Native Image) |
| Memory | High | Low |
| GraalVM Native | Hard | First-class support |
How AOT works:
1. Maven/Gradle plugin runs the process-aot goal.
2. Analyses @Configuration, @Component, bean dependencies.
3. Generates plain Java code (no reflection): bean definitions, proxy classes, reflection hints.
4. The code compiles alongside app code.
mvn spring-boot:process-aot # generates AOT code
mvn -Pnative native:compile # build native imageConstraints:
- Cannot register beans dynamically at runtime (BeanDefinitionRegistryPostProcessor is restricted).
- Reflection requires explicit hints (@RegisterReflectionForBinding).
- Conditional beans (@ConditionalOnProperty) resolve at build time, not runtime.
Use cases: combined with GraalVM Native Image for serverless (Lambda), CLI tools, microservices needing fast scale-to-zero.