Notes 01
Notes 01
🔹 WHY DI?
Loose coupling
Easy testing
Reusability
@Component
class Car {
Engine engine;
Engine engine;
@Autowired
public void setEngine(Engine engine) {
[Link] = engine;
}
}
@Autowired
Engine engine;
}
⚠️ Interview Tip:
👉 Always say:
✔ Constructor Injection is best practice
🧠 SPRING BEAN
🔹 DEFINITION
👉 A Bean is an object managed by the Spring container.
🏷️ IMPORTANT SPRING ANNOTATIONS (WITH
DEFINITIONS + EXAMPLES)
🔹 @COMPONENT
DEFINITION
👉 Marks a class as a Spring Bean.
EXAMPLE
@Component
class Engine {}
🔹 @SERVICE
DEFINITION
👉 Used for business logic layer.
EXAMPLE
@Service
class UserService {
public void saveUser() {}
}
🔹 @REPOSITORY
DEFINITION
👉 Used for database layer and handles exceptions.
EXAMPLE
@Repository
class UserRepository {
public void save() {}
}
🔹 @CONTROLLER
DEFINITION
👉 Handles web requests (MVC).
EXAMPLE
@Controller
class MyController {
@RequestMapping("/home")
public String home() {
return "[Link]";
}
}
🔹 @RESTCONTROLLER
DEFINITION
👉 Used to create REST APIs (returns JSON/text).
EXAMPLE
@RestController
class ApiController {
@GetMapping("/api")
public String getData() {
return "Data";
}
}
🔹 @AUTOWIRED
DEFINITION
👉 Automatically injects dependency.
EXAMPLE
@Autowired
Engine engine;
🔹 @QUALIFIER
DEFINITION
👉 Used when multiple beans exist to specify which one to inject.
EXAMPLE
@Autowired
@Qualifier("dieselEngine")
Engine engine;
🔹 @SPRINGBOOTAPPLICATION
DEFINITION
👉 Main configuration annotation (combines 3 annotations).
EXAMPLE
@SpringBootApplication
public class App {
public static void main(String[] args) {
[Link]([Link], args);
}
}
@Repository Database
@RestController
class UserController {
@Autowired
UserService service;
@GetMapping("/user")
public String user() {
return [Link]();
}
✅ DI (3 types)
✅ Bean & lifecycle
✅ All important annotations
✅ Real usage in project