Java示例代码展示 Spring如何配置集成Tomcat服务器

猿友 2021-08-03 10:24:53 浏览数 (2132)
反馈

Tomcat因技术先进、性能稳定、而且免费,深受Java程序员的喜好以及开发商的认可,是当下最流行的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();
    // 设置监听端口
		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 服务器的文章就介绍到这了,想要了解更多相关 Java Web应用服务器 Tomcat 的其他内容请搜索W3Cschool以前的文章或继续浏览下面的相关文章,也希望大家以后多多支持!


0 人点赞