web服务启动执行顺序:
1、判断是否指定了动态参数如:-Dspring.profiles.active=dev,加载application-dev.properties文件等,
2、判断是否是web环境,加载xml文件
3、启动web服务器
4、加载属性配置文件
5、扫描实体进行注册
6、指定服务端口号
启动Spring-boot时:
1、先通过一个简单的查找Servlet的类的方式来判断是否是web环境
private static final String[] WEB_ENVIRONMENT_CLASSES = { "javax.servlet.Servlet",
"org.springframework.web.context.ConfigurableWebApplicationContext" };
private boolean deduceWebEnvironment() {
for (String className : WEB_ENVIRONMENT_CLASSES) {
if (!ClassUtils.isPresent(className, null)) {
return false;
}
}
return true;
}
如果是web环境:
则创建AnnotationConfigEmbeddedWebApplicationContext类,进行初始化xml文件,
否则创建AnnotationConfigApplicationContext类
//org.springframework.boot.SpringApplication
protected ConfigurableApplicationContext createApplicationContext() {
Class<?> contextClass = this.applicationContextClass;
if (contextClass == null) {
try {
contextClass = Class.forName(this.webEnvironment
? DEFAULT_WEB_CONTEXT_CLASS : DEFAULT_CONTEXT_CLASS);
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Unable create a default ApplicationContext, "
+ "please specify an ApplicationContextClass",
ex);
}
}
return (ConfigurableApplicationContext) BeanUtils.instantiate(contextClass);
}
2、获取EmbeddedServletContainerFactory的实现类
spring boot通过获取EmbeddedServletContainerFactory来启动对应的web服务器。
常用的两个实现类是TomcatEmbeddedServletContainerFactory、JettyEmbeddedServletContainerFactory
启动tomcat的代码:
//TomcatEmbeddedServletContainerFactory
@Override
public EmbeddedServletContainer getEmbeddedServletContainer(
ServletContextInitializer... initializers) {
Tomcat tomcat = new Tomcat();
File baseDir = (this.baseDirectory != null ? this.baseDirectory
: createTempDir("tomcat"));
tomcat.setBaseDir(baseDir.getAbsolutePath());
Connector connector = new Connector(this.protocol);
tomcat.getService().addConnector(connector);
customizeConnector(connector);
tomcat.setConnector(connector);
tomcat.getHost().setAutoDeploy(false);
tomcat.getEngine().setBackgroundProcessorDelay(-1);
for (Connector additionalConnector : this.additionalTomcatConnectors) {
tomcat.getService().addConnector(additionalConnector);
}
prepareContext(tomcat.getHost(), initializers);
return getTomcatEmbeddedServletContainer(tomcat);
}