🧾 Spring Boot Annotations Cheat Sheet (Beginner Friendly)
✅ 1. Application Setup
Annotation | Purpose | Analogy | Example |
@SpringBootApplication | Main entry point, enables auto-setup and scanning | Restaurant Manager | @SpringBootApplication |
@ComponentScan | Finds beans in current and sub-packages | Hiring staff from known places | @ComponentScan("com.example") |
@EnableAutoConfiguration | Auto-configures beans based on libraries | Smart Assistant | Used inside @SpringBootApplication |
@Configuration | Declares a class with manual bean definitions | Kitchen Blueprint | @Configuration |
🧱 2. Creating Beans
Annotation | Purpose | Analogy | Example |
@Component | Marks a class as a Spring bean | Generic Worker | @Component |
@Service | Marks a class as business logic | Cook or Chef | @Service |
@Repository | Marks a class that talks to DB | Cashier or Clerk | @Repository |
@Controller | Handles HTTP requests (HTML/UI) | Waiter or Host | @Controller |
@RestController | Same as controller, but returns JSON | Waiter with takeout bag | @RestController |
@Bean | Registers a manual bean | Custom order from kitchen | @Bean public Coffee coffee() |
🤝 3. Dependency Injection
Annotation | Purpose | Analogy | Example |
@Autowired | Injects bean automatically | Manager assigning tools | @Autowired Coffee coffee; |
@Qualifier | Chooses specific bean when multiple are present | Choosing between brands | @Autowired @Qualifier("hot") |
@Value | Injects value from properties file | Filling in a form | @Value("${app.name}") |
@Primary | Makes a bean the default choice if multiple exist | Favorite worker | @Primary |
🔄 4. Bean Scopes
Annotation | Purpose | Analogy | Example |
@Scope("singleton") | Only one shared instance | Shared office printer | Default behavior |
@Scope("prototype") | New object every time | Disposable cup | @Scope("prototype") |
@Scope("request") | One per web request | One shopping cart per visit | Web app only |
@Scope("session") | One per user session | Your Netflix login session | Web app only |
Use with:
@Component
@Scope(value = "prototype")
🌐 5. Web-Specific
Annotation | Purpose | Analogy | Example |
@GetMapping | Handles GET requests | Ask for a menu | @GetMapping("/coffee") |
@PostMapping | Handles POST requests | Submit an order | @PostMapping("/order") |
@PathVariable | Extracts value from URL | “/coffee/123” → 123 | @GetMapping("/coffee/{id}") |
@RequestParam | Extracts query parameter | ?type=hot | @RequestParam("type") |
@RequestBody | Extracts JSON from request | Whole order on a paper | @PostMapping + @RequestBody |
🔐 6. Security & Lifecycle (Advanced, optional)
Annotation | Purpose | Analogy | Example |
@PostConstruct | Method runs after bean init | Cook sets table after cooking | @PostConstruct void init() |
@PreDestroy | Method runs before shutdown | Clean up before closing | @PreDestroy void cleanup() |
@Secured, @RolesAllowed | Role-based access | Only chef can access kitchen | @Secured("ROLE_ADMIN") |