gpt4 book ai didi

java - Spring MVC - DispatcherServlet 通过注释

转载 作者:行者123 更新时间:2023-12-03 07:33:24 24 4
gpt4 key购买 nike

我得到了 Spring 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 注释初始化。那么我该如何初始化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("/");
}

}

关于java - Spring MVC - DispatcherServlet 通过注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16707152/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com