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();
    // 設置監聽端口
		tomcat.setPort(PORT);
		tomcat.getHost().setAppBase(".");
    // 這裡 Connector 不存在,自動創建一個 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();
	}
}

也可以自己創建一個Connector指定端口

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

創建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的?

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

例如:Spring中的ServletContainerInitializer實現類SpringServletContainerInitializer會調用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) {
      // 調用WebApplicationInitializer實現類的onStartup方法
			initializer.onStartup(servletContext);
		}
	}

}

image-20210413234957179

到此這篇關於Spring通過Java配置集成Tomcat的文章就介紹到這瞭,更多相關Spring配置集成Tomcat內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀:

    None Found