joplin-notes/joplin notion extension/Web Development/Java/Spring/Getting started.md
2026-11-04 00:33:23 +05:30

48 lines
1.4 KiB
Markdown

Getting started
**Dependency injection**
https://www.youtube.com/watch?v=J1f5b4vcxCQ : Dependeny injection, the best pattern
Dependency
- there r functions or objects that use other objects or functions and they r called dependency. There are 2 types of coupling.
1. Hard coupling: Here dependency cant be changed
2. Loose coupling: To change dependency in future
 
Dependency injection
- Instead of instantiating new code in constructor or function in same braces/scope we pass it instead through parameter to be used.
- Main goal of dependency injection is to achieve loose coupling.
eg
without DI(Dependency Injection)
```java
public class Laptop{
HardDrive obj1 = new HitachiHD();
}
```
with DI
```java
public class Laptop{
HardDrive obj1;
Laptop(HardDrive obj){
this.obj1= obj;
}
}
```
- It is possible using external service. That service is responsible for creating objects.
- Example in spring boot
```java
class Laptop{
@Autowired
HardDrive obj1;
}
@Component
class HitachiHD implements HardDrive{
// ...
}
```
With this `@Autorired` annotation it will find the component which is tagged by `@Component` to connect to it.
- Not only this is useful to prevent tight coupling, but also for testing.
When we wanna test laptop
then we may not need to check harddrive bcz it is already tested so with these we can separate it too. We can create *mock object* of the class if it is loosely coupled.