Java.Servlet.What is 1 in loadOnStartup = 1 ?

The 1 in loadOnStartup = 1 (or <load-on-startup>1</load-on-startup>) is an integer priority that tells the servlet container:

👉 “Load this servlet when the application starts — and do it in this order relative to other servlets.”

🔢 What Does the Number Mean?

✅ Non-negative Integer (0, 1, 2, etc.)

  • Tells the container to load the servlet eagerly, at application startup.
  • Lower numbers load first.
  • Multiple servlets? Order of loading is based on ascending numbers.
ValueEffect
0Load immediately (high priority)
1Load after 0
5Load later

So if you have:

<load-on-startup>1</load-on-startup>  // InitServlet
<load-on-startup>2</load-on-startup>  // MetricsServlet

Then InitServlet is initialized before MetricsServlet.

❌ Negative or Absent Value

  • Servlet is loaded lazily — only when it receives its first request.
  • This is the default behavior if load-on-startup is not specified.

🚀 Use Cases for loadOnStartup

ScenarioWhy Set Priority?
DB connection pool initializationEnsure DB is ready before user requests
Logging system bootstrappingStart logs early
Caching dataPreload and warm up cache
Background schedulersStart worker threads early

✅ Example with Annotation

@WebServlet(urlPatterns = "/init", loadOnStartup = 1)
public class InitServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        System.out.println("🚀 InitServlet started at app startup!");
    }
}

This entry was posted in Без рубрики. Bookmark the permalink.