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.
Value | Effect |
---|---|
0 | Load immediately (high priority) |
1 | Load after 0 |
5 | Load 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
Scenario | Why Set Priority? |
---|---|
DB connection pool initialization | Ensure DB is ready before user requests |
Logging system bootstrapping | Start logs early |
Caching data | Preload and warm up cache |
Background schedulers | Start 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!");
}
}