Tomcat Java Servlet - Initialize Class on Application Startup

后端 未结 3 1799
名媛妹妹
名媛妹妹 2020-12-30 09:01

I have a class that takes a bit of time to start up (makes some JNI calls and what not), so it is not feasable to initialize this class everytime a page loads. Is it possibl

相关标签:
3条回答
  • 2020-12-30 09:41

    You can do the initialize of the class inside the servlet's init method.
    init() method is invoked when the servlet instance is loaded so it is a good place for expensive operations.

    0 讨论(0)
  • 2020-12-30 09:45

    If you want it to happen once for the whole app, and happen before any servlet is run, implement ServletContextListener and put your startup code in contextInitialized(). Then set up your web.xml to specify your class as a listener.

    Otherwise, you can do what the other answer says and put it in the init() method of the servlet.

    0 讨论(0)
  • 2020-12-30 09:51

    You have two choices:

    1. Initialize your class in servlet's init() method. You may add <load-on-startup> attribute to make sure your servlet is created at application startup and not on first access.

    2. Add ServletContextListener and use contextInitialized() callback method. Use ServletContext#setAttribute to store created object for future use.

    0 讨论(0)
提交回复
热议问题