gpt4 book ai didi

java - Spring 启动 |多个调度程序 Servlet

转载 作者:行者123 更新时间:2023-12-01 16:46:24 24 4
gpt4 key购买 nike

我从一个新的 Spring Boot 应用程序开始,我需要有两个 Dispatcher servlet。我正在做这样的事情:

public class ApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {

AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(AppConfig.class);

container.addListener(new ContextLoaderListener(rootContext));

AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
dispatcherContext.register(DispatcherConfig.class);

ServletRegistration.Dynamic uiDispatcher = container.addServlet("uiDispatcher",
new DispatcherServlet(dispatcherContext));
uiDispatcher.setLoadOnStartup(1);
uiDispatcher.setInitParameter("initializeJ2EE", "false");
uiDispatcher.addMapping("/ui/*");

ServletRegistration.Dynamic utilDispatcher = container.addServlet("utilDispatcher",
new DispatcherServlet());
utilDispatcher.setLoadOnStartup(1);
utilDispatcher.setInitParameter("initializeJ2EE", "false");
utilDispatcher.addMapping("/util/*");

container.addListener(new ContextLoaderListener(rootContext));
}

这看起来是正确的做法吗?过去,我从未需要使用“WebApplicationInitializer”来启动应用程序。如果我需要多个 Dispatcher servlet,是否需要这样做,或者是否有更好的方法来处理这个问题?

最佳答案

是的,确实如此。 Spring 为我们提供了 web.xmlWebApplicationInitializer 来配置 DispatcherServlet(甚至是两者的混合)。如果您对多个 DispathcherServletweb.xml 感兴趣。这是一个例子

<servlet>
<description>Monitor</description>
<servlet-name>monitor</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>monitor</servlet-name>
<url-pattern>/monitor</url-pattern>
</servlet-mapping>

<servlet>
<description>Metrics</description>
<servlet-name>metrics</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>metrics</servlet-name>
<url-pattern>/metrics/</url-pattern>
</servlet-mapping>

关于java - Spring 启动 |多个调度程序 Servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61766320/

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