-1

This is related to the question How do i get servlet instance from web.xml in my java class

Folks were not clear as to what is the usecase for this type of question. I have the same question and wanted to give a usecase.

In my application i have a class called Configuration which extends HttpServlet. In my web.xml i have an load-on-startup servlet defined for Configuration. This class reads all the properties necessary for the application, and it is absolutely necessary that this properties are read during startup because there something which i am doing differently for each instance of my webserver based on the properties. Now i need to get a handle of this instance in my spring controllers so that i can get the values of the properties. How do i do it?

Community
  • 1
  • 1
Abdus Samad
  • 343
  • 2
  • 12
  • 27

1 Answers1

1

Is there any specific reason why Configuration is a Servlet? If this class's sole purpose is to read properties to be used later and it is not serving any requests by itself, it shouldn't be a Servlet.

There are two ways to do these configuration classes.

One, you can annotate this class as a @Component and make this class to be instantiated by Spring during startup. Then you can inject this bean wherever you need it.

Second way, without using Spring, is to register an ServletContextListener in your web.xml. Create a class implement the ServletContextListener and inside the contextInitialized() method, call the method of the Configuration class where your property loading logic resides.

http://www.mkyong.com/servlet/what-is-listener-servletcontextlistener-example/

RKodakandla
  • 3,318
  • 13
  • 59
  • 79