Spring Boot Internals: Reflection + Annotations
Spring Boot heavily relies on annotations and reflection to reduce boilerplate code. Instead of manually creating objects, Spring scans classes, detects annotations, and injects dependencies automatically.
Core Idea
- Annotations → Mark what needs to be done
- Reflection → Executes it at runtime
- Container → Manages objects (Beans)
How @Autowired Works Internally
When Spring sees @Autowired, it uses reflection to find the required dependency and inject it into the field.
class Engine {}
class Car {
@Autowired
private Engine engine;
}Internal steps:
- Scan classpath for classes
- Detect @Autowired field
- Use reflection to access private field
- Find matching object (bean)
- Inject using field.set(obj, value)
Mini Spring Simulation (Custom DI)
import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Inject {}
class Engine {}
class Car {
@Inject
private Engine engine;
public void show() {
System.out.println(engine != null ? "Engine Injected" : "NULL");
}
}
public class Main {
public static void main(String[] args) throws Exception {
Car car = new Car();
for (Field f : car.getClass().getDeclaredFields()) {
if (f.isAnnotationPresent(Inject.class)) {
f.setAccessible(true);
f.set(car, new Engine());
}
}
car.show();
}
}Output
Engine InjectedAOP (Aspect-Oriented Programming)
Spring uses annotations like @Transactional or @Log to wrap methods dynamically using proxies and reflection.
- Method is intercepted
- Extra logic added (logging, transactions)
- Original method is executed
Bean Creation Flow
- Scan classes (@Component, @Service)
- Create objects using reflection
- Store in container
- Inject dependencies
- Return when needed
Tricky Interview Questions
- Difference between getField() and getDeclaredField()
- Why setAccessible(true) is needed?
- Why reflection is slow?
- What is RetentionPolicy.RUNTIME?
- How does @Autowired work internally?
- Can we modify private final fields using reflection?
- What is the role of Class object?
Tricky Scenario
What happens if you forget RUNTIME retention?
@Retention(RetentionPolicy.CLASS) // WRONG
@interface Test {}👉 Reflection will NOT see this annotation at runtime → injection fails silently.
Real-World Usage
- @Autowired → Dependency Injection
- @RestController → API creation
- @Entity → Database mapping (Hibernate)
- @Transactional → Transaction management
Final Summary
- Annotations define WHAT
- Reflection defines HOW
- Spring connects both
- Used for DI, AOP, ORM
- Core concept for backend developers