Naman Gala
Naman Gala

Reputation: 4692

Which approach should I use to inject 10+ services in Spring controller?

I am developing Spring mvc application.

I have a controller in which I am injecting more than 10 Services.

I am exposing 10+ url from this controller and at a time I am using one or two service objects in each method.

I was thinking of 2 approaches.

  1. Directly inject all services using @Autowired.
  2. Fetch Service from ApplicationContext at runtime whenever required.

Please suggest me which approach is better or both approach are equal in terms of memory usage and time

Thanks

Upvotes: 2

Views: 163

Answers (1)

geoand
geoand

Reputation: 64011

The best approach in most cases is to break up the controller into multiple controllers. Having too many dependencies is a Code Smell since your controller most likely violates the Single Responsibility Principle.

Both using @Autowired for many dependencies and using the ApplicationContext to dynamically retrieve the dependency are mediocre solutions in most cases and should be avoided whenever possible. What you should do is break up the controller and then use @Autowired (preferably constructor rather than field injection - check out this for more details) to make Spring inject the dependencies.

In the case you describe you should not be worried about the performance or the memory consumption of your proposed solutions, but the maintanability of the code.

Although dynamic lookup of a dependency from the ApplicationContext will be a little slower that accesing the injected by the container dependency, in almost all cases you we never be able to tell the difference. As I mentioned above, the first concern you must be looking at is code maintanability, not micro-performance/memory issues.

Upvotes: 8

Related Questions