Spring boot dependency injection
Hello everyone , today i am going write about how to use depency injection in spring boot application and what are the usage of dependency injection..
The one of main advantage of dependency injection is make our application more loosely coupling.
To achive that spring make object for us automatically..
Spring create object for us using two reational design patterns..
- Singleton Design Pattern -- Create instance of the object .
- Prototype Design Pattern -- Create multiple objects.
Lets try ..
1. create interface named Hardware .
public interface Hardware {
void provideHardware();
}
2. create POJO named SamsungHardware that implements Hardware interface.
@Component
public class SamsungHardWare implements Hardware {
private String name;
public SamsungHardWare() {
System.out.println("Create object of samsung hardware!");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void provideHardware() {
System.out.println("Providing hardware");
}
}
using component annotation we tell spring to make object for us.. then spring create bean named SamsungHardware inside spring container.
3. create POJO named Laptop.
@Component
public class Laptop {
private String brand;
private int version;
@Autowired
private Hardware hardWare;
public Laptop() {
System.out.println("Object of Laptop has been created!");
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public void assemble() {
System.out.println("Laptop in assembling!!");
hardWare.provideHardware();
}
}
This Laptop class depends on Hardware objects. so that we have reffer hardware objects inside spring container using autowired annotation. using autowired spring find necessary object for us and inject into Laptop class. So we don’t have to create object manually using new keyword.. spring make object for us and connect with that necessary object .. This will make more loosely coupling our spring application..
4. Lets use laptopn inside in our main method.
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(DependencyInjectionApplication.class, args);
Laptop l1 = context.getBean(Laptop.class);
l1.assemble();
}
context is use for access bean class inside spring container.
Check above screenshot about out put of our programe. We can see spring create objects for us of both Laptop and Hardware classes. Thats dependency injection will be more usefull when building complex applications..
So thats the end of my today article .. Please follow me if you intersted more topics like this.. thank you..