简体   繁体   中英

Spring - is using new a bad practice?

Is creating objects by hand , ie 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?

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.

Object creation should not dependent on classes. When you use new operator it creats a dependency which is pain point for you ie you have to worry about this object creation When u do change in constructor. Here where the object globalization helps. Autowiring the object reduces the dependencies completely. If you dont use this feature you will get to know yourself anyways.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM