亲宝软件园·资讯

展开

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

面试官认为我什么都会 人气:0
想了解Spring通过Java配置集成Tomcat的方法的相关内容吗,面试官认为我什么都会在本文为您仔细讲解Spring配置集成Tomcat的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Spring配置集成Tomcat,Spring集成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

加载全部内容

相关教程
猜你喜欢
用户评论