繁体   English   中英

Spring MVC-通过注释的DispatcherServlet

[英]Spring MVC - DispatcherServlet by annotations

我有春季MVC应用程序。 它运行在Tomcat 7上。现在,我在web.xml文件中获得了这一部分:

<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注释@Bean 那么我如何在那里初始化DispatherServlet

这是带有注释的示例。 希望这对您有所帮助。

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("/");
    }

}

之所以这样写,是因为Japs的答案导致了另一个上下文的创建,而该上下文看不到安全上下文的内容。

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[] { "/" };
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM