好吧,我终于通过查看Tomcat7源代码解决了它,即在处理EmbeddedTomcat和Servlet 3.0批注的单元测试中。
基本上,您必须像这样启动Embedded Tomcat 7,以使其了解带注释的类:
String webappDirLocation = "src/main/webapp/";
Tomcat tomcat = new Tomcat();
tomcat.setPort(8080);
StandardContext ctx = (StandardContext) tomcat.addWebapp("/embeddedTomcat",
new File(webappDirLocation).getAbsolutePath());
//declare an alternate location for your "WEB-INF/classes" dir:
File additionWebInfClasses = new File("target/classes");
VirtualDirContext resources = new VirtualDirContext();
resources.setExtraResourcePaths("/WEB-INF/classes=" + additionWebInfClasses);
ctx.setResources(resources);
tomcat.start();
tomcat.getServer().await();
为了清楚起见,我应该提到这适用于标准的Maven项目,在该项目中可以在以下位置找到“ Web资源”(例如静态和动态页面,WEB-INF目录等):
[您项目的根目录] / src / main / webapp
你的班级被编译成
[您项目的根目录] /目标/类
(这样,您将拥有[您的项目的根目录] / target / classes / [某些软件包] /SomeCompiledServletClass.class)
对于其他目录布局,需要相应地更改这些位置。
====更新:嵌入式Tomcat 8 ====
感谢@kwak注意到这一点。
API进行了一些更改,以下是使用嵌入式Tomcat 8时上述示例的变化:
String webappDirLocation = "src/main/webapp/";
Tomcat tomcat = new Tomcat();
tomcat.setPort(8080);
StandardContext ctx = (StandardContext) tomcat.addWebapp("/embeddedTomcat",
new File(webappDirLocation).getAbsolutePath());
//declare an alternate location for your "WEB-INF/classes" dir:
File additionWebInfClasses = new File("target/classes");
WebResourceRoot resources = new StandardRoot(ctx);
resources.addPreResources(new DirResourceSet(resources, "/WEB-INF/classes", additionWebInfClasses.getAbsolutePath(), "/"));
ctx.setResources(resources);
tomcat.start();
tomcat.getServer().await();