1

If i can solve dependency injection using normal constructors or using setter methods, What is the use of Dependency injection framework such as spring which is solely developed for the purpose of Dependnecy injection ?

darshan kamat
  • 301
  • 5
  • 16
  • Possible duplicate of [What is dependency injection?](https://stackoverflow.com/questions/130794/what-is-dependency-injection) – Karol Dowbecki Mar 18 '18 at 12:15
  • 1
    My advice to you. First read about loose coupling before starting with dependency injection. – Jagger Mar 18 '18 at 12:21

1 Answers1

1

Because you don't have to care for getting you dependency from class to class. All that is done by Spring using a IoC-Container, which contains all beans (java classes which are annotated with @Component, @Service, ...). These beans have, per default, a singleton-scope.

This enables you to

@Autowire
private MyBean bean

let spring inject the one (singleton) instance of "MyBean". With the @Autowire-Annotation you tell spring to inject the instance of MyBean. And it just works. No need for caring about how you get that one instance of "MyBean" over to any classes - they will be injected automatically.

watchme
  • 680
  • 6
  • 23
  • alternative to field injection is constructor based injection,lets say i m using constructor injection..why i need spring then ? – darshan kamat Mar 18 '18 at 12:20
  • Because you don't have to handle your instance over to that class - spring will do that for you by using the IoC-Container. – watchme Mar 18 '18 at 12:21
  • @darshankamat Well, because then you are hard coding your dependencies? – Jagger Mar 18 '18 at 12:22
  • @Jagger wouldn't you also hard-code your dependencies if you used Autowiring at the constructor? Isn't this the same effect? If you use autowiring at the constructor, or just handle it over, you depend always on the same classes/instances. – watchme Mar 18 '18 at 12:53
  • @watchme Not if I autowire interfaces and not classes. It's the whole point of having an IoC container, isn't it? – Jagger Mar 18 '18 at 13:20
  • With interfaces you perform loose coupling, thats right. IoC in Spring, as I understood it, just means that you give the control of injecting instances of a class to the framework. If you autowire an interface, or a class, doesn't matter. Its just that IoC is often combined with loose coupling, but in fact, those two are different concepts. – watchme Mar 18 '18 at 13:41
  • If I got someting wrong, feel free to correct me, I am still in the beginning of learning Spring. – watchme Mar 18 '18 at 13:49
  • @Jagger #morelettersinordertocomment – watchme Mar 18 '18 at 16:04