Spring Dependency Injection: Autowired, Inject, Resource

🔍 @Autowired vs @Inject vs @Resource in Spring In Spring, there are three annotations used for Dependency Injection: 1️⃣ @Autowired 2️⃣ @Inject 3️⃣ @Resource They all inject dependencies, but they come from different specifications and follow different rules. 1️⃣ @Autowired 📌 Provided by: Spring Framework 📌 Package: 'org.springframework.beans.factory.annotation.Autowired' Key Points ✔ Injects dependency by type ✔ Most commonly used in Spring ✔ Supports @Qualifier for resolving multiple beans Example @Autowired private UserService userService; If multiple beans exist: @Autowired @Qualifier("userServiceImpl") private UserService userService; 2️⃣ @Inject 📌 Provided by: Java Dependency Injection (JSR-330) 📌 Package: 'javax.inject.Inject' Key Points ✔ Works similar to @Autowired ✔ Injects dependency by type ✔ Framework independent (not only Spring) Example @Inject private UserService userService; If multiple beans exist: @Inject @Named("userServiceImpl") private UserService userService; 3️⃣ @Resource 📌 Provided by: Java EE (JSR-250) 📌 Package: javax.annotation.Resource Key Points ✔ Injects dependency by name first ✔ If name not found → fallback to type Example @Resource private UserService userService; Or explicitly: @Resource(name = "userServiceImpl") private UserService userService; 🧠 Simple Way to Remember @Autowired → Spring style injection @Inject → Java standard DI @Resource → Name-based injection #SpringBoot #SpringFramework #Java #DependencyInjection #BackendDevelopment

To view or add a comment, sign in

Explore content categories