App下載

Java示例代碼展示 Spring如何配置集成Tomcat服務器

猿友 2021-08-03 10:24:53 瀏覽數(shù) (2265)
反饋

Tomcat因技術先進、性能穩(wěn)定、而且免費,深受Java程序員的喜好以及開發(fā)商的認可,是當下最流行的Web應用服務器。下面,我將和大家分享Spring項目中如何通過Java來配置集成Tomcat服務器。

添加Tomcat依賴

<!-- 自己編譯的版本-->
<dependency>
    <groupId>org.apache</groupId>
    <artifactId>apache-tomcat-9.0.36-src</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

首先需要一個tomcat啟動類

public class TomcatRun {

	private static final int PORT = 8080;
	private static final String CONTEXT_PATH = "/com/yu";

	public static void main(String[] args) {
		Tomcat tomcat = new Tomcat();
    // 設置監(jiān)聽端口
		tomcat.setPort(PORT);
		tomcat.getHost().setAppBase(".");
    // 這里 Connector 不存在,自動創(chuàng)建一個 Connector,并將 tomcat 的端口賦值給 Connector
		tomcat.getConnector();
		tomcat.addWebapp(CONTEXT_PATH, new File("src/main/webapp").getAbsolutePath());
		try {
			tomcat.start();
		} catch (LifecycleException e) {
			e.printStackTrace();
		}
		tomcat.getServer().await();
	}
}

也可以自己創(chuàng)建一個Connector指定端口

// 手動創(chuàng)建 connector
// Connector connector = new Connector();
// connector.setPort(PORT);
// tomcat.getService().addConnector(connector);

創(chuàng)建Spring配置

public class MyWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class[]{RootConfig.class};
	}

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

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

	@Override
	protected Filter[] getServletFilters() {
		return new Filter[]{
				//
				new CharacterEncodingFilter(StandardCharsets.UTF_8.name())
		};
	}
}

這里就結束了。。。


問題來了Tomcat是怎么啟動Sping的?

實現(xiàn)了Servlet3.0的容器(例如Tomcat)會掃描classpath*下面的META-INF/services/javax.servlet.ServletContainerInitializer文件,里面指定ServletContainerInitializer的實現(xiàn),另外還有一個注解HandlesTypes表達對某個類感興趣,在調(diào)用onStartup方法時會將HandlesTypes指定接口的實現(xiàn)類傳遞進來。

例如:Spring中的ServletContainerInitializer實現(xiàn)類SpringServletContainerInitializer會調(diào)用WebApplicationInitializeronStartup方法,也就是上面定義的MyWebApplicationInitializer父類的onStartup,這里就會相繼完成AnnotationConfigWebApplicationContextDispatcherServlet的初始化

@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer {

	@Override
	public void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)
			throws ServletException {

		List<WebApplicationInitializer> initializers = new LinkedList<>();

		if (webAppInitializerClasses != null) {
			for (Class<?> waiClass : webAppInitializerClasses) {
				// Be defensive: Some servlet containers provide us with invalid classes,
				// no matter what @HandlesTypes says...
				if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
						WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
					try {
						initializers.add((WebApplicationInitializer)
								ReflectionUtils.accessibleConstructor(waiClass).newInstance());
					}
					catch (Throwable ex) {
						throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
					}
				}
			}
		}

		if (initializers.isEmpty()) {
			servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
			return;
		}

		servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
		AnnotationAwareOrderComparator.sort(initializers);
		for (WebApplicationInitializer initializer : initializers) {
      // 調(diào)用WebApplicationInitializer實現(xiàn)類的onStartup方法
			initializer.onStartup(servletContext);
		}
	}

}

image-20210413234957179

到此這篇關于 Spring 通過 Java 來實現(xiàn)配置集成 Tomcat 服務器的文章就介紹到這了,想要了解更多相關 Java Web應用服務器 Tomcat 的其他內(nèi)容請搜索W3Cschool以前的文章或繼續(xù)瀏覽下面的相關文章,也希望大家以后多多支持!


0 人點贊