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?
CodePudding user response:
If you use new
keyword, then Service
need to know how Dao1
and Dao2
are implemented and instantiated(concrete type, parameters...), more knowledge means more coupling.
However, if you use @Autowired
, then Spring do everything for you by Dependency Injection
technique, the coupling becomes more loosely.
The advantage of loosely coupling is: your code becomes more testable and maintainable.
CodePudding user response:
You should read about the many benefits of dependency injection, this is a good place to start: https://en.m.wikipedia.org/wiki/Dependency_injection.
But if you want a short one line answer its main benefit is that it makes the code easier to test.
If you create the DAO classes with the new keyword in your service class you cannot easily replace them with mock objects during testing of the service class.
CodePudding user response:
First, note that field injection has been discouraged by Spring for several years now. Second, dependency injection alone does not magically guarantee loose coupling. Abstraction is also necessary. Since there is no abstraction in these examples, Service
is coupled just as tightly to the Dao
implementations whether you inject or instantiate them.
Spring still offers other benefits here, including lifecycle management and cohesion. Also note that since the Dao
classes are not final
, there is potential for abstraction, because Spring could inject subclasses whereas direct instantiation will always give you the base class.