Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring 3.1 WebApplicationInitializer&;嵌入式Jetty 8注释配置_Java_Spring Mvc_Jetty_Embedded Jetty_Jetty 8 - Fatal编程技术网

Java Spring 3.1 WebApplicationInitializer&;嵌入式Jetty 8注释配置

Java Spring 3.1 WebApplicationInitializer&;嵌入式Jetty 8注释配置,java,spring-mvc,jetty,embedded-jetty,jetty-8,Java,Spring Mvc,Jetty,Embedded Jetty,Jetty 8,我正在尝试使用Spring3.1和嵌入式Jetty8服务器创建一个没有任何XML配置的简单webapp 然而,我正努力让Jetty认可我的SpringWebApplicationInitializer接口的实现 项目结构: src +- main +- java | +- JettyServer.java | +- Initializer.java | +- webapp +- web.xml (objective

我正在尝试使用Spring3.1和嵌入式Jetty8服务器创建一个没有任何XML配置的简单webapp

然而,我正努力让Jetty认可我的SpringWebApplicationInitializer接口的实现

项目结构:

src
 +- main
     +- java
     |   +- JettyServer.java
     |   +- Initializer.java
     | 
     +- webapp
         +- web.xml (objective is to remove this - see below).
上面的Initializer类是WebApplicationInitializer的一个简单实现:

同样,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的注释实现;它应该找到初始值设定项并将其连接到

但是,当我启动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.5servlet是有意义的(见下文),但是当使用AnnotationConfiguration时应该是什么呢

注意:如果我将配置更改为以下设置,则所有设置都会正确启动:

...
webAppContext.setConfigurations(new Configuration[] { new WebXmlConfiguration() });
...
在本例中,它在src/main/webapp下找到web.xml,并使用它以通常的方式使用DispatcherServlet和AnnotationConfigWebApplicationContext连接servlet(完全绕过上面的WebApplicationInitializer实现)

这感觉很像一个类路径问题,但我很难理解Jetty是如何将自己与WebApplicationInitializer的实现联系在一起的——任何建议都将不胜感激

关于信息,我使用以下内容:

...
webAppContext.setConfigurations(new Configuration[] { new WebXmlConfiguration() });
...
春季3.1.1 码头8.1.7
STS3.1.0

基于我的测试和这个线程,我认为它目前不起作用。如果在AnnotationConfiguration.configure中查找:

   parseContainerPath(context, parser);
   // snip comment
   parseWebInfClasses(context, parser);
   parseWebInfLib (context, parser);
它似乎与类似战争的部署相结合,而不是嵌入

下面是一个使用Spring MVC和嵌入式Jetty的示例,可能更有用:


它直接创建Spring servlet,而不是依赖于注释。

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

如果我注册了
AnnotationConfiguration
的子类,它会找到我的
WebApplicationInitializer
,该子类会覆盖
configure(WebAppContext)
以扫描主机类路径以及容器和web inf位置

大多数子类(遗憾的是)都是从父类复制粘贴的。它包括:

  • configure方法末尾的额外解析调用(
    parseHostClassPath
  • parseHostClassPath
    方法,主要是从
    AnnotationConfiguration
    parseWebInfClasses
  • 获取第一个非jar URL的
    getHostClassPathResource
    方法 从类加载器(至少对我来说,它是我的 eclipse中的类路径)
我使用的Jetty(8.1.7.v20120910)和Spring(3.1.2_发行版)的版本略有不同,但我认为相同的解决方案也会起作用

编辑:我在github中创建了一个工作示例项目,并做了一些修改(下面的代码在Eclipse中可以正常工作,但在着色jar中运行时却不行)——

在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;                    
            }
        },
    });
webAppContext.setConfigurations(新配置[]
{
新的AnnotationConfiguration()
{
@凌驾
public void configure(WebAppContext上下文)引发异常
{
布尔metadataComplete=context.getMetaData().isMetaDataComplete();
addDecorator(新注释decorator(context));
AnnotationParser=null;
如果(!metadataComplete)
{
if(context.getServletContext().getEffectiveMajorVersion()>=3 | | context.isConfiguration发现())
{
parser=createAnnotationParser();
registerNotationHandler(“javax.servlet.annotation.WebServlet”,新的WebServletAnnotationHandler(上下文));
registerNotationHandler(“javax.servlet.annotation.WebFilter”,新的WebFilterNotationHandler(上下文));
registerNotationHandler(“javax.servlet.annotation.WebListener”,新的WebListenerAnnotationHandler(上下文));
}
}
List nonExcludedInitializers=getNonExcludedInitializers(上下文);
parser=registerServletContainerInitializerAnnotationHandlers(上下文、解析器、非排除的初始化器);
if(解析器!=null)
{
parseContainerPath(上下文,解析器);
ParseWebInfClass(上下文、解析器);
parseWebInfLib(上下文,解析器);
parseHostClassPath(上下文,解析器);
}                  
}
私有void parseHostClassPath(最终WebAppContext上下文,AnnotationParser)引发异常
{
clearAnnotationList(parser.getAnnotationHandlers());
Resource Resource=getHostClassPathResource(getClass().getClassLoader());
if(资源==null)
返回;
parser.parse(资源,新ClassNameResolver()
{
公共布尔值IsExclude(字符串名称)
{           
if(context.isSystemClass(name))返回true;
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();                 
            }
        }
    });
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);
        }
    }
});
public static void main(String[] args) throws Exception {
    Server server = new Server();
    ServerConnector scc = new ServerConnector(server);
    scc.setPort(Integer.parseInt(System.getProperty("jetty.port", "8080")));
    server.setConnectors(new Connector[] { scc });

    WebAppContext context = new WebAppContext();
    context.setServer(server);
    context.setContextPath("/");
    context.setWar("src/main/webapp");
    context.getMetaData().addContainerResource(new FileResource(new File("./target/classes").toURI()));
    context.setConfigurations(new Configuration[]{
            new WebXmlConfiguration(),
            new AnnotationConfiguration()
    });

    server.setHandler(context);

    try {
        System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP");
        System.out.println(String.format(">>> open http://localhost:%s/", scc.getPort()));
        server.start();
        while (System.in.available() == 0) {
            Thread.sleep(5000);
        }
        server.stop();
        server.join();
    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(100);
    }

}
    ClassList cl = Configuration.ClassList.setServerDefault(server);
    cl.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration", "org.eclipse.jetty.annotations.AnnotationConfiguration");
@Component
public class Initializer implements WebApplicationInitializer {

    private ServletContext servletContext;

    @Autowired
    public WebInitializer(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    @PostConstruct
    public void onStartup() throws ServletException {
        onStartup(servletContext);
    }

    public void onStartup(ServletContext servletContext) throws ServletException {
        System.out.println("onStartup");
    }
}
        context.setConfigurations(
            new org.eclipse.jetty.webapp.Configuration[] { new WebXmlConfiguration(), new AnnotationConfiguration() {
                @Override
                public void preConfigure(WebAppContext context) throws Exception {
                    final ClassInheritanceMap map = new ClassInheritanceMap();
                    final ConcurrentHashSet<String> set = new ConcurrentHashSet<>();
                    set.add(MyWebAppInitializer.class.getName());
                    map.put(WebApplicationInitializer.class.getName(), set);
                    context.setAttribute(CLASS_INHERITANCE_MAP, map);
                    _classInheritanceHandler = new ClassInheritanceHandler(map);
                }
            } });
context.setExtraClasspath(pathsToWebJarsCommaSeparated);
context.setAttribute(WebInfConfiguration.WEBINF_JAR_PATTERN, ".*\\.jar$");
context.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, ".*\\.jar$");
context.setConfigurations(
        new org.eclipse.jetty.webapp.Configuration[] { 
        new WebInfConfiguration(), new MetaInfConfiguration(),
        new AnnotationConfiguration() {
            @Override
            public void preConfigure(WebAppContext context) throws Exception {
                final ClassInheritanceMap map = new ClassInheritanceMap();
                final ConcurrentHashSet<String> set = new ConcurrentHashSet<>();
                set.add(MyWebAppInitializer.class.getName());
                map.put(WebApplicationInitializer.class.getName(), set);
                context.setAttribute(CLASS_INHERITANCE_MAP, map);
                _classInheritanceHandler = new ClassInheritanceHandler(map);
            }
        } });
webAppContext.setAttribute(AnnotationConfiguration.CLASS_INHERITANCE_MAP, createClassMap());
private ClassInheritanceMap createClassMap() {
    ClassInheritanceMap classMap = new ClassInheritanceMap();
    ConcurrentHashSet<String> impl = new ConcurrentHashSet<>();
    impl.add(MyWebAppInitializer.class.getName());
    classMap.put(WebApplicationInitializer.class.getName(), impl);
    return classMap;
}
public class Main {

public static void main(String... args) throws Exception {
    Properties properties = new Properties();
    InputStream stream = Main.class.getResourceAsStream("/WEB-INF/application.properties");
    properties.load(stream);
    stream.close();
    PropertyConfigurator.configure(properties);

    WebAppContext webAppContext = new WebAppContext();
    webAppContext.setResourceBase("resource");
    webAppContext.setContextPath(properties.getProperty("base.url"));
    webAppContext.setConfigurations(new Configuration[] {
        new WebXmlConfiguration(),
        new AnnotationConfiguration() {
            @Override
            public void preConfigure(WebAppContext context) {
                ClassInheritanceMap map = new ClassInheritanceMap();
                map.put(WebApplicationInitializer.class.getName(), new ConcurrentHashSet<String>() {{
                    add(WebInitializer.class.getName());
                    add(SecurityWebInitializer.class.getName());
                }});
                context.setAttribute(CLASS_INHERITANCE_MAP, map);
                _classInheritanceHandler = new ClassInheritanceHandler(map);
            }
        }
    });

    Server server = new Server(Integer.parseInt(properties.getProperty("base.port")));
    server.setHandler(webAppContext);
    server.start();
    server.join();
}
}
    public class Console {
    public static void main(String[] args) {
        try {
            Server server = new Server(8080);

            //Set a handler to handle requests.
            server.setHandler(getWebAppContext());

            //starts to listen at 0.0.0.0:8080
            server.start();
            server.join();
        } catch (Exception e) {
            log.error("server exited with exception", e);
        }
    }

    private static WebAppContext getWebAppContext() {
        final WebAppContext webAppContext = new WebAppContext();

        //route all requests via this web-app.
        webAppContext.setContextPath("/");

        /*
         * point to location where the jar into which this class gets packaged into resides.
         * this could very well be the target directory in a maven development build.
         */
        webAppContext.setResourceBase("directory_where_the_application_jar_exists");

        //no web inf for us - so let the scanning know about location of our libraries / classes.
        webAppContext.getMetaData().setWebInfClassesDirs(Arrays.asList(webAppContext.getBaseResource()));

        //Scan for annotations (servlet 3+)
        final AnnotationConfiguration configuration = new AnnotationConfiguration();
        webAppContext.setConfigurations(new Configuration[]{configuration});

        return webAppContext;
    }
}