Spring is famous with it Inverse Control and DI.
I know that dependency injection have several ways like Constructor Dependency Injection etc.
for example
we usually use @Autowired
annotation to do Dependency Injection.
when we develop MVC web project.
My question is very simple
Why is a spring framework loosely coupled?
Suppose We have two Dao class One is Dao1 ,other is Dao2
Dao1
public class Dao {
public void sayhi() {
System.out.println("hello");
}
}
Dao2
public class Dao2 {
public void saygoodbye() {
System.out.println("say goodbye");
}
}
If we do not use Autowired
annotation
the service should be
public class Service {
Dao1 dao=new Dao1();
Dao2 dao2=new Dao2();
public void sayhi() {
dao.sayhi();
}
public void saygoodbye() {
dao2.saygoodbye();
}
}
and the Controller should be
@RestController
public class Controller {
Service service=new Service( );
@GetMapping("test")
public void saysomething() {
service.saygoodbye();
service.sayhi();
}
}
If we do not use Autowired
annotation , we must use new keyword to make instance
If we use Autowired
annotation
the code
Dao1 dao=new Dao1();
Dao2 dao2=new Dao2();
just change it into
@Autowired
Dao1 dao
@Autowired
Dao2 dao2
So,without Autowired annotation
Why is a spring framework loosely coupled?
Aucun commentaire:
Enregistrer un commentaire