javamavenjerseyinitializationservlet-container

Can Jersey's ServletContainer init method be overridden?


Writing a Web Service in Java (Jersey/Maven). I'd like to construct a class that builds a number of databases before the application is deployed - as all of its resources depend on those databases. Although there is a textual representation of the Jersey's ServletContainer source code, it has already been compiled into bytecode and packed into a jar and, thus, cannot be edited. Is the solution as simple as declaring an instance of the ServletContainer class in my code and overriding the init method there?


Solution

  • You can just do all your initialization in the ResourceConfig.

    package org.foo;
    
    public class AppConfig extends ResourceConfig {
        public AppConfig() {
            // initialize here
            packages("the.packages.to.scan");
        }
    }
    

    And you can declare it in the web.xml

    <web-app>
        <servlet>
            <servlet-name>MyApplication</servlet-name>
            <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
            <init-param>
                <param-name>javax.ws.rs.Application</param-name>
                <param-value>org.foo.AppConfig</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>MyApplication</servlet-name>
            <url-pattern>/api/*</url-pattern>
        </servlet-mapping>
    </web-app>
    

    For other deployment options see Servlet-based Deployment