'Spring - is using new a bad practice?

Is creating objects by hand, i.e. using new operator instead of registering Spring bean and using dependency injection considered bad practice? I mean, does Spring IoC container have to know about all objects in the application? If so, why?



Solution 1:[1]

Spring implements the Dependency Injection pattern. You should inject in the container of spring the beans that are going to be used in other classes as dependence to be able to work. Usually classes that implement interfaces are injected so that if you change the implementation, the classes that use that interface do not know about the change.

I recommend you read the post about the dependency injection of Martin Fowler.

Solution 2:[2]

Using new is not bad and you are just giving the IoC container the responsibility of using new under the hood. IoC will know about all the classes that you register with it. When using frameworks, it's even more important to think about the applications architecture, because a framework makes bad design as easy to implement as good design.

If you don't need multiple implementations of a class, then use new.

If you think it's plausible that you may need to switch between implementations, consider your app design and find a suitable injection point so that refactoring won't be such a drain.

If you need multiple implementation of a class, then use a design pattern like a factory or a DI framework.

Not every nook and cranny of an application needs to be highly configurable. That's what leads to over-engineered and hard to maintain code.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 J T