首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring MVC - DispatcherServlet by annotations

Spring MVC - DispatcherServlet by annotations
EN

Stack Overflow用户
提问于 2013-05-23 14:38:01
回答 2查看 16.1K关注 0票数 2

我得到了spring MVC应用程序。它在Tomcat7上运行。到目前为止,我在web.xml文件中得到了这一部分:

代码语言:javascript
复制
<servlet>
        <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                /WEB-INF/app-config.xml
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>

有没有办法通过注解来初始化它?我得到了一个MainSettings.java类,其中我所有的bean都由@Bean注释初始化。那么我如何在那里初始化DispatherServlet呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-05-23 17:21:19

以下是带有注释的示例。希望这对你有帮助。

代码语言:javascript
复制
public class ApplicationInitializer implements WebApplicationInitializer {

    //Called first when the application starts loading.
    public void onStartup(ServletContext servletContext)
            throws ServletException {
        System.out.println("Inside application initializer...");

        //Registering the class that incorporates the annotated DispatcherServlet configuration of spring
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(DispatcherConfig.class);

        //Adding the listener for the rootContext
        servletContext.addListener(new ContextLoaderListener(rootContext));

        //Registering the dispatcher servlet mappings.
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }

}
票数 5
EN

Stack Overflow用户

发布于 2014-10-09 20:37:26

之所以这样写,是因为Japs's answer会导致创建另一个上下文,该上下文看不到安全上下文的内容。

代码语言:javascript
复制
public class WebInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {

    private static final Log LOGGER = LogFactory.getLog(WebInitializer.class);

    @Override
    protected Class<?>[] getRootConfigClasses() {
        /*  this is where you will return you config class
         *  your root config class should @Import other configs 
         *  to make them work without needing them to add there
         */
        return new Class[] { ViewConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[0];
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16707152

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档