我试图使用Spring 3.1和嵌入式Jetty 8服务器创建一个简单的web应用程序,而不需要任何XML配置。
然而,我无法让Jetty识别我的Spring WebApplicationInitializer接口实现。
项目结构:
src
+- main
+- java
| +- JettyServer.java
| +- Initializer.java
|
+- webapp
+- web.xml (objective is to remove this - see below).
上面的Initializer类是WebApplicationInitializer的简单实现:
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.springframework.web.WebApplicationInitializer;
public class Initializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
System.out.println("onStartup");
}
}
同样,JettyServer是嵌入式Jetty服务器的简单实现:
import org.eclipse.jetty.annotations.AnnotationConfiguration;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.WebAppContext;
public class JettyServer {
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
WebAppContext webAppContext = new WebAppContext();
webAppContext.setResourceBase("src/main/webapp");
webAppContext.setContextPath("/");
webAppContext.setConfigurations(new Configuration[] { new AnnotationConfiguration() });
webAppContext.setParentLoaderPriority(true);
server.setHandler(webAppContext);
server.start();
server.join();
}
}
据我理解,Jetty在启动时将使用AnnotationConfiguration来扫描带注释的ServletContainerInitializer实现;它应该能够找到Initializer并加以连接...
然而,当我从Eclipse中启动Jetty服务器时,在命令行中看到以下内容:
2012-11-04 16:59:04.552:INFO:oejs.Server:jetty-8.1.7.v20120910
2012-11-04 16:59:05.046:INFO:/:No Spring WebApplicationInitializer types detected on classpath
2012-11-04 16:59:05.046:INFO:oejsh.ContextHandler:started o.e.j.w.WebAppContext{/,file:/Users/duncan/Coding/spring-mvc-embedded-jetty-test/src/main/webapp/}
2012-11-04 16:59:05.117:INFO:oejs.AbstractConnector:Started SelectChannelConnector@0.0.0.0:8080
重要的部分是这个:
No Spring WebApplicationInitializer types detected on classpath
请注意,src/main/java在Eclipse中被定义为源文件夹,因此应该在类路径中。还要注意动态Web模块Facet设置为3.0。
我相信有一个简单的解释,但我很难看清楚问题所在!我怀疑关键在于以下行:
...
webAppContext.setResourceBase("src/main/webapp");
...
当使用web.xml(见下文)的2.5 servlet时,这是有意义的,但是如果使用AnnotationConfiguration,应该是什么呢?
注意:如果我将配置更改为以下内容,则一切都会正确启动:
...
webAppContext.setConfigurations(new Configuration[] { new WebXmlConfiguration() });
...
在这种情况下,它会在`src/main/webapp`目录下找到`web.xml`文件,并使用`DispatcherServlet`和`AnnotationConfigWebApplicationContext`来通常的方式来连接Servlet(完全绕过上面实现的`WebApplicationInitializer`)。这感觉非常像一个类路径问题,但我很难理解Jetty如何将其与`WebApplicationInitializer`的实现关联起来 - 任何建议都将不胜感激!
信息:
Spring 3.1.1 Jetty 8.1.7 STS 3.1.0