App下載

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

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

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

添加Tomcat依賴(lài)

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

首先需要一個(gè)tomcat啟動(dòng)類(lèi)

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();
    // 設(shè)置監(jiān)聽(tīng)端口
		tomcat.setPort(PORT);
		tomcat.getHost().setAppBase(".");
    // 這里 Connector 不存在,自動(dòng)創(chuàng)建一個(gè) 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)建一個(gè)Connector指定端口

// 手動(dòng)創(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())
		};
	}
}

這里就結(jié)束了。。。


問(wèn)題來(lái)了Tomcat是怎么啟動(dòng)Sping的?

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

例如:Spring中的ServletContainerInitializer實(shí)現(xiàn)類(lèi)SpringServletContainerInitializer會(huì)調(diào)用WebApplicationInitializeronStartup方法,也就是上面定義的MyWebApplicationInitializer父類(lèi)的onStartup,這里就會(huì)相繼完成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實(shí)現(xiàn)類(lèi)的onStartup方法
			initializer.onStartup(servletContext);
		}
	}

}

image-20210413234957179

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


0 人點(diǎn)贊