one of the most important features of spring is that it provides decoupling using dependency injection. like I have an interface Vehicle and I have its implementations like Car, Bus, Bike. so I can configure these beans in spring and can assign any implementations out of Car, Bus, Bike into Vehicle. so the code is loosely coupled here, but same thing we can achieve here using factory pattern, in this way also we will have to change the code at the only one place while passing the information to the factory method. so I want to know that how spring is more efficient here, I mean why we should use spring if we can achieve same decoupling using factory pattern ?
-
can you clarify what you mean by efficient? – LuckyLikey Jan 16 '19 at 07:17
-
I mean why should we use spring if factory provides same facility ? – K Rupesh Jan 16 '19 at 08:57
-
Possible duplicate of [Dependency Injection vs Factory Pattern](https://stackoverflow.com/questions/557742/dependency-injection-vs-factory-pattern) – jaco0646 Jan 16 '19 at 15:20
1 Answers
The difference is that Using Spring or any other IoC Framework will do much more than only create objects (beans in spring terms) for you.
The IoC Controller does:
- Create Objects
- Manage Objects lifetime
- Inject inner dependencies
- allow you to add Scopes
just to name a few things.
Read this blog for more information about IoC with spring, and if you're interested in Scopes read this.
How is Spring more efficient in decoupling the classes?
For Performance Purposes, it really depends on how you implement your Factories. On what you are trying to do.
However it does do a much better Job at decoupling classes. As you can see with all the built in features you can use. So it simplifies many things a lot and does save you a lot of boilerplate code. One thing I want to point out is that it doesn't prevent you from using factories at all, too. For example you can use FactoryBean which provides Factories using the Spring IoC mechanics.

- 3,504
- 1
- 31
- 54
-
thank you for your response, does spring uses factory pattern itself internally ? – K Rupesh Jan 16 '19 at 08:55
-
why I got -1 vote for my question what is wrong here ? my one account already got blocked due to this. – K Rupesh Jan 16 '19 at 08:56
-
@KRupesh I dont know spring that well, but usally IoC Containers are implemented differently. If I answered your question, consider accepting it and / or give some credits by upvoting. – LuckyLikey Jan 16 '19 at 10:33
-
@KRupesh The reason, why you might have got downvotes on your question is, because it's not that easy to answer a question asked being a little broad. Next time write the Question more in a Q&A Style and also consider this article [ask] – LuckyLikey Jan 16 '19 at 10:35