How is appContext.getBean() any better than new?

I dont get how appContext.getBean() is beneficial than creating the object using new.
Yeah, i read the line that says that it is useful when you have lot of components to be used.
But if the member objects are created internally in the constructor instead of passing as parameter, that issue is avoided. Tight coupling is avoided by use of interface and say I want to switch from ContentBasedFilter to CollaborativeFilter, how is moving the @Component annotation any better than changing the code to use the different class? Compilation and delivery of jars to the customer is needed in both the cases.
On the contrary, if I want to do something like read a config file and at runtime pick the right class, the @Component is useless, right?
Atleast at this moment, Spring looks like too much overengineering for little or no benefit which on the contrary is making things difficult to maintain and understand by introducing hidden “magic” to the code.


Hi @Amol2, Thanks for reaching out to us.
The ApplicationContext interface provides the getBean() method to retrieve the bean from the spring container. ApplicationContext represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the beans. The container gets its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata.
The appContext.getBean() is beneficial because it provides the following:

  • Bean factory methods for accessing application components
  • The ability to load file resources in a generic way
  • The ability to publish events to registered listeners
  • The ability to resolve messages, supporting internationalization

Calling ApplicationContext.getBean() is not Inversion of Control! While it’s still easy to change what implementation is configured for the given bean name, the class now relies directly on Spring to provide that dependency and can’t get it any other way. You can’t just make your own mock implementation in a test class and pass that to it yourself.
This basically defeats Spring’s purpose as a dependency injection container. Dependency injection is more suited to larger programs. Most of the time the additional complexity is not worth it. One of the coolest benefits of using something like Spring is that you don’t have to wire your objects together.

Hope it will help :slight_smile:

1 Like