close
應用程式內嵌Jetty運行webapp時,希望程式和webapp共用同一個spring context,在web.xml設定context loader listener時,要改用自定的MyContextLoaderListener。
JettyServer.java:
import org.mortbay.jetty.Server; import org.mortbay.jetty.nio.SelectChannelConnector; import org.mortbay.jetty.webapp.WebAppContext; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class JettyServer implements ApplicationContextAware { private ApplicationContext applicationContext; public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public void start() throws Exception { int port = Integer.parseInt(System.getProperty("jetty.port", "8080")); SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(port); Server server = new Server(); server.addConnector(connector); WebAppContext context = new WebAppContext(); context.setClassLoader(applicationContext.getClassLoader()); context.setAttribute("applicationContext", applicationContext); context.setServer(server); context.setContextPath("/"); context.setWar("src/main/webapp"); server.addHandler(context); server.start(); } }
MyContextLoader.java:
import javax.servlet.ServletContext; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.web.context.ContextLoader; public class MyContextLoader extends ContextLoader { @Override protected ApplicationContext loadParentContext(ServletContext servletContext) throws BeansException { return (ApplicationContext)servletContext.getAttribute("applicationContext"); } }
MyContextLoaderListener.java:
import org.springframework.web.context.ContextLoader; import org.springframework.web.context.ContextLoaderListener; public class MyContextLoaderListener extends ContextLoaderListener { @Override protected ContextLoader createContextLoader() { return new MyContextLoader(); } }
全站熱搜