Spring 3.1 WebApplicationInitializer & Embedded Jetty 8 AnnotationConfiguration

我正在尝试使用Spring 3.1和嵌入式Jetty 8服务器创建一个简单的webapp,而无需任何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将使用NotificationConfiguration来扫描ServletContainerInitializer的注释实现;它应该找到初始值设定项并将其连接在...

但是,当我启动Jetty服务器(从Eclipse内部)时,我在命令行上看到以下内容:

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 模块方面设置为 3.0。

我相信有一个简单的解释,但我正在努力看到树木的木材!我怀疑关键是以下行:

...
webAppContext.setResourceBase("src/main/webapp");
...

对于使用web.xml的2.5 servlet来说,这是有道理的(见下文),但是当使用NotescriptConfiguration时,它应该是什么?

注意:如果我将配置更改为以下内容,则一切都会正确启动:

...
webAppContext.setConfigurations(new Configuration[] { new WebXmlConfiguration() });
...

在这种情况下,它在src/main/webapp下找到web.xml,并使用它以通常的方式使用DispmenterServletNoteationConfigWebApplicationContext来连接servlet(完全绕过上面的WebApplicationInitializer实现)。

这感觉非常像一个类路径问题,但我很难理解Jetty如何将自己与WebApplicationInitializer的实现相关联 - 任何建议将不胜感激!

有关信息,我正在使用以下内容:

弹簧 3.1.1 码头 8.1.7 STS 3.1.0


答案 1

问题在于 Jetty 的类不会扫描类路径上的非 jar 资源(WEB-INF/类下除外)。AnnotationConfiguration

如果我注册一个子类,它会找到我的,该子类除了容器和web-inf位置之外,还会覆盖以扫描主机类路径。WebApplicationInitializerAnnotationConfigurationconfigure(WebAppContext)

大多数子类(可悲地)是从父类复制粘贴的。它包括:

  • 在配置方法的末尾有一个额外的解析调用 ();parseHostClassPath
  • 该方法很大程度上是从 的 复制粘贴parseHostClassPathAnnotationConfigurationparseWebInfClasses;
  • 从类加载器中获取第一个非jar URL的方法(至少对我来说,它是 eclipse 中我的类路径的文件 url)。getHostClassPathResource

我使用的是略有不同的Jetty(8.1.7.v20120910)和Spring(3.1.2_RELEASE)版本,但我想同样的解决方案会起作用。

编辑:我在github中创建了一个工作示例项目,并进行了一些修改(下面的代码在Eclipse中工作正常,但在阴影罐中运行时则不然) - https://github.com/steveliles/jetty-embedded-spring-mvc-noxml

在OP的JettyServer类中,必要的更改将第15行替换为:

webAppContext.setConfigurations (new Configuration []
{
        new AnnotationConfiguration() 
        {
            @Override
            public void configure(WebAppContext context) throws Exception
            {
                boolean metadataComplete = context.getMetaData().isMetaDataComplete();
                context.addDecorator(new AnnotationDecorator(context));   

                AnnotationParser parser = null;
                if (!metadataComplete)
                {
                    if (context.getServletContext().getEffectiveMajorVersion() >= 3 || context.isConfigurationDiscovered())
                    {
                        parser = createAnnotationParser();
                        parser.registerAnnotationHandler("javax.servlet.annotation.WebServlet", new WebServletAnnotationHandler(context));
                        parser.registerAnnotationHandler("javax.servlet.annotation.WebFilter", new WebFilterAnnotationHandler(context));
                        parser.registerAnnotationHandler("javax.servlet.annotation.WebListener", new WebListenerAnnotationHandler(context));
                    }
                }

                List<ServletContainerInitializer> nonExcludedInitializers = getNonExcludedInitializers(context);
                parser = registerServletContainerInitializerAnnotationHandlers(context, parser, nonExcludedInitializers);

                if (parser != null)
                {
                    parseContainerPath(context, parser);
                    parseWebInfClasses(context, parser);
                    parseWebInfLib (context, parser);
                    parseHostClassPath(context, parser);
                }                  
            }

            private void parseHostClassPath(final WebAppContext context, AnnotationParser parser) throws Exception
            {
                clearAnnotationList(parser.getAnnotationHandlers());
                Resource resource = getHostClassPathResource(getClass().getClassLoader());                  
                if (resource == null)
                    return;

                parser.parse(resource, new ClassNameResolver()
                {
                    public boolean isExcluded (String name)
                    {           
                        if (context.isSystemClass(name)) return true;                           
                        if (context.isServerClass(name)) return false;
                        return false;
                    }

                    public boolean shouldOverride (String name)
                    {
                        //looking at webapp classpath, found already-parsed class of same name - did it come from system or duplicate in webapp?
                        if (context.isParentLoaderPriority())
                            return false;
                        return true;
                    }
                });

                //TODO - where to set the annotations discovered from WEB-INF/classes?    
                List<DiscoveredAnnotation> annotations = new ArrayList<DiscoveredAnnotation>();
                gatherAnnotations(annotations, parser.getAnnotationHandlers());                 
                context.getMetaData().addDiscoveredAnnotations (annotations);
            }

            private Resource getHostClassPathResource(ClassLoader loader) throws IOException
            {
                if (loader instanceof URLClassLoader)
                {
                    URL[] urls = ((URLClassLoader)loader).getURLs();
                    for (URL url : urls)
                        if (url.getProtocol().startsWith("file"))
                            return Resource.newResource(url);
                }
                return null;                    
            }
        },
    });

更新:Jetty 8.1.8 引入了与上述代码不兼容的内部更改。对于 8.1.8,以下内容似乎有效:

webAppContext.setConfigurations (new Configuration []
    {
        // This is necessary because Jetty out-of-the-box does not scan
        // the classpath of your project in Eclipse, so it doesn't find
        // your WebAppInitializer.
        new AnnotationConfiguration() 
        {
            @Override
            public void configure(WebAppContext context) throws Exception {
                   boolean metadataComplete = context.getMetaData().isMetaDataComplete();
                   context.addDecorator(new AnnotationDecorator(context));   


                   //Even if metadata is complete, we still need to scan for ServletContainerInitializers - if there are any
                   AnnotationParser parser = null;
                   if (!metadataComplete)
                   {
                       //If metadata isn't complete, if this is a servlet 3 webapp or isConfigDiscovered is true, we need to search for annotations
                       if (context.getServletContext().getEffectiveMajorVersion() >= 3 || context.isConfigurationDiscovered())
                       {
                           _discoverableAnnotationHandlers.add(new WebServletAnnotationHandler(context));
                           _discoverableAnnotationHandlers.add(new WebFilterAnnotationHandler(context));
                           _discoverableAnnotationHandlers.add(new WebListenerAnnotationHandler(context));
                       }
                   }

                   //Regardless of metadata, if there are any ServletContainerInitializers with @HandlesTypes, then we need to scan all the
                   //classes so we can call their onStartup() methods correctly
                   createServletContainerInitializerAnnotationHandlers(context, getNonExcludedInitializers(context));

                   if (!_discoverableAnnotationHandlers.isEmpty() || _classInheritanceHandler != null || !_containerInitializerAnnotationHandlers.isEmpty())
                   {           
                       parser = createAnnotationParser();

                       parse(context, parser);

                       for (DiscoverableAnnotationHandler h:_discoverableAnnotationHandlers)
                           context.getMetaData().addDiscoveredAnnotations(((AbstractDiscoverableAnnotationHandler)h).getAnnotationList());      
                   }

            }

            private void parse(final WebAppContext context, AnnotationParser parser) throws Exception
            {                   
                List<Resource> _resources = getResources(getClass().getClassLoader());

                for (Resource _resource : _resources)
                {
                    if (_resource == null)
                        return;

                    parser.clearHandlers();
                    for (DiscoverableAnnotationHandler h:_discoverableAnnotationHandlers)
                    {
                        if (h instanceof AbstractDiscoverableAnnotationHandler)
                            ((AbstractDiscoverableAnnotationHandler)h).setResource(null); //
                    }
                    parser.registerHandlers(_discoverableAnnotationHandlers);
                    parser.registerHandler(_classInheritanceHandler);
                    parser.registerHandlers(_containerInitializerAnnotationHandlers);

                    parser.parse(_resource, 
                                 new ClassNameResolver()
                    {
                        public boolean isExcluded (String name)
                        {
                            if (context.isSystemClass(name)) return true;
                            if (context.isServerClass(name)) return false;
                            return false;
                        }

                        public boolean shouldOverride (String name)
                        {
                            //looking at webapp classpath, found already-parsed class of same name - did it come from system or duplicate in webapp?
                            if (context.isParentLoaderPriority())
                                return false;
                            return true;
                        }
                    });
                }
            }

            private List<Resource> getResources(ClassLoader aLoader) throws IOException
            {
                if (aLoader instanceof URLClassLoader)
                {
                    List<Resource> _result = new ArrayList<Resource>();
                    URL[] _urls = ((URLClassLoader)aLoader).getURLs();                      
                    for (URL _url : _urls)
                        _result.add(Resource.newResource(_url));

                    return _result;
                }
                return Collections.emptyList();                 
            }
        }
    });

答案 2

我能够以一种更简单但更有限的方式解决,只需向NotesalConfiguration显式提供实现类(在本例中为MyWebApplicationInitializerImpl),我希望像这样加载:

webAppContext.setConfigurations(new Configuration[] {
    new WebXmlConfiguration(),
    new AnnotationConfiguration() {
        @Override
        public void preConfigure(WebAppContext context) throws Exception {
            MultiMap<String> map = new MultiMap<String>();
            map.add(WebApplicationInitializer.class.getName(), MyWebApplicationInitializerImpl.class.getName());
            context.setAttribute(CLASS_INHERITANCE_MAP, map);
            _classInheritanceHandler = new ClassInheritanceHandler(map);
        }
    }
});

推荐