2. Code Example

The code excerpt below is from EmbeddedPersonServiceClientTest, and is run before any of the tests are run to initialize Jetty. Even though this is a unit test, this would be the same code that would be used to start a standalone Spring application. It could contain an executor pool, db connection pool, timer processes, etc.

The main application context is initialized, and then the Jetty Server bean is retrieved from it. Then the ServletContext from the Spring Web Services webapp is retrieved. An intermediary web application context is created between the main application context and the Spring Web Services context. The intermediary web context is then set as an attribute on the ServletContext under the constant WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, which indicates it should be used as the parent context for the web application. Then the Jetty server is ready to be started.

Example 1. EmbeddedPersonServiceClientTest

                
AbstractApplicationContext ctx = 
    new ClassPathXmlApplicationContext("/org/springbyexample/ws/embedded/embedded-jetty-context.xml");  1
ctx.registerShutdownHook();

Server server = (Server) ctx.getBean("jettyServer");  2

ServletContext servletContext = null;

for (Handler handler : server.getHandlers()) {
    if (handler instanceof Context) {
        Context context = (Context) handler;
        
        servletContext = context.getServletContext();3
    }
}

XmlWebApplicationContext wctx = new XmlWebApplicationContext();  4
wctx.setParent(ctx);
wctx.setConfigLocation("");
wctx.setServletContext(servletContext);
wctx.refresh();

servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wctx);  5

server.start();  6
                
            

1 Create the main application context which has Jetty configured in it.
2 Retrieve the Jetty server bean.
3 Retrieve the ServletContext from the Spring Web Services webapp. The context path of the Context doesn't need to be checked because it's the only Context configured.
4 Create a web application context as an intermediary between the main application context and the webapp's context.
5 Set created web application context as the parent context of the web application by setting it on the ServletContext under the WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE constant.
6 Starts the Jetty server.