Spring通过Java配置集成Tomcat的方法

添加Tomcat依赖



    org.apache
    apache-tomcat-9.0.36-src
    1.0-SNAPSHOT

首先需要一个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> webAppInitializerClasses, ServletContext servletContext)
			throws ServletException {

		List 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);
		}
	}

}

Spring通过Java配置集成Tomcat的方法_第1张图片

到此这篇关于Spring通过Java配置集成Tomcat的文章就介绍到这了,更多相关Spring配置集成Tomcat内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(Spring通过Java配置集成Tomcat的方法)