Search code examples
javaspringdependency-injectioninversion-of-controlnew-operator

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

  • You want Spring to create beans for classes that :

    • you want/need to inject instance(s) in other beans
    • you need to inject beans (or dependencies) in their own instances.
    • you want them to benefit from Spring features (instantiation management, transaction management, proxy classes Spring empowered such as Repository/Interceptor and so for...)

    Services, controllers or interceptors are example of them.
    For example a controller may need inject a service or an interceptor.
    As well as you don't want to handle the instantiation of these classes by implementing yourself the singleton pattern for each one. Which could be error-prone and require boiler plate code.
    So you want all of these classes to be beans managed by Spring.

    But you don't want to Spring create beans for classes that :

    • you don't want/need to inject instance(s) in other beans
    • you don't need to inject beans (or rdependencies) in their own instances
    • you don't need them benefit from Spring features

    Entity, DTO, Value Object are example of them.

    For example an entity never needs to be injected into another entity or in a service as a dependency because entities are not created at the container startup but are generally created inside a method and have a scope limited to the methods lifespan.
    As well as you don't need Spring to create instances which the lifespan is a method. The new operator does very well the job.
    So defining them as bean instances makes no sense and appears even counter intuitive.