-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInjection.java❤️💉
More file actions
58 lines (45 loc) · 1.71 KB
/
Injection.java❤️💉
File metadata and controls
58 lines (45 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
Spring Dependency Injection Example
This project demonstrates how to use Spring’s @Autowired annotation for Dependency Injection (DI) in Java. It helps developers write cleaner, more maintainable code without manually instantiating objects.
What is Dependency Injection?
Dependency Injection (DI) is a design pattern where an object receives its dependencies from an external source rather than creating them itself.
The object doesn’t need to use new.
Spring automatically creates and injects the required objects.
Makes code easier to test, maintain, and extend.
Why @Autowired?
@Autowired tells Spring to inject the required bean automatically. It can be applied to:
Fields
Constructor
Setter methods
Example:
@Component
class Engine {
public void start() {
System.out.println("Engine started");
}
}
@Component
class Car {
@Autowired
private Engine engine; // Spring injects this automatically
public void drive() {
engine.start();
System.out.println("Car is driving");
}
}
Here:
No new Engine() is needed.
Spring manages creation and lifecycle of Engine.
Car can just use the engine directly.
How to Run
Clone the repo:
git clone https://github.com/yourusername/spring-di-example.git
Open in your favorite IDE (IntelliJ, Eclipse).
Run the Spring Boot application.
Observe the automatic injection in action.
Benefits
Cleaner code – no manual new statements.
Easier testing – you can inject mock objects.
Better maintainability – dependencies are managed centrally by Spring.
Flexible – you can swap implementations easily.
Fun Fact
The term “Injection” in Dependency Injection makes it sound like Spring has a magic needle that injects objects directly where needed! 😄