1

I was wondering when I should use setServletContext.setAttribute(), at the start up of the application, to store data.

I suppose I should use it to store data that I share among many classes of my web application.

For example: so far, I had a website in which I read the address, emails etc from a .properties file. I print address, emails etc in many pages, so I created a class (ConfigurationData.class) which reads that .properties file, and every class that need to know address, email etc "@Autowires" the ConfigurationData.class.

I was wondering if instead of @Autowired ConfigurationData.class in many other classes I should use setServletContext.setAttribute() at the start up of the application.

Which solution "use" less server resources?

Since every "@Autowired" class is a singleton, using many time "@Autowired" for the same class shoudn't be "heavy" for the server, should be?

Thank you in advance.

MDP
  • 4,177
  • 21
  • 63
  • 119

1 Answers1

1

Which solution I should use ?

It is always better to use @Autowired ConfigurationData option because you can inject this object anywhere (like in service layers etc..) inside your application, where as servletcontext object you can use only in front end layers (like controllers). So obviously, using @Autowired ConfigurationData is the best option.

Since every "@Autowired" class is a singleton, using many time "@Autowired" for the same class shoudn't be "heavy" for the server, should be?

Using @Autowired many times for the same class does NOT create many objects (unless you are changing the default singleton scope of the bean), rather they use the same object with a different reference. Also, one more point is that even if you want to use servletcontext object, you need to use @Autowired in your controller (rather than accessing from HttpServletRequest), you can look at here

Which solution "use" less server resources?

It will not make a big difference because both of them are singleton objects. However, when it comes to performance and resource usage, you need to benchmark your application and then find out the bottlenecks. Surely, in general, these small things do not become bottlenecks for the application.

Community
  • 1
  • 1
Vasu
  • 21,832
  • 11
  • 51
  • 67