判断改类是否在项目中加载

1
2
3
# 判断改类是否在项目中加载
boolean present = ClassUtils.isPresent("ch.qos.logback.access.db.DBAppender", null);

springboot 源码 入口:this.webApplicationType = WebApplicationType.*deduceFromClasspath*();

springboot 会判断 他是否是

  1. 反应式web应用程序运行,并应启动嵌入式反应式web服务器
  2. 为基于servlet的web应用程序运行,并且应该启动嵌入式servlet web服务器
  3. 程序不应作为web应用程序运行,也不应启动嵌入式web服务器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private static final String WEBMVC_INDICATOR_CLASS = "org.springframework.web.servlet.DispatcherServlet";

private static final String WEBFLUX_INDICATOR_CLASS = "org.springframework.web.reactive.DispatcherHandler";

private static final String JERSEY_INDICATOR_CLASS = "org.glassfish.jersey.servlet.ServletContainer";

static WebApplicationType deduceFromClasspath() {
if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null) && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
&& !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {
return WebApplicationType.REACTIVE;
}
for (String className : SERVLET_INDICATOR_CLASSES) {
if (!ClassUtils.isPresent(className, null)) {
return WebApplicationType.NONE;
}
}
return WebApplicationType.SERVLET;
}

设置初始化器(Initializer)

setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static final String *FACTORIES_RESOURCE_LOCATION* = "META-INF/spring.factories";

Enumeration<URL> urls = classLoader.getResources(FACTORIES_RESOURCE_LOCATION);
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
UrlResource resource = new UrlResource(url);
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
for (Map.Entry<?, ?> entry : properties.entrySet()) {
String factoryTypeName = ((String) entry.getKey()).trim();
String[] factoryImplementationNames =
StringUtils.commaDelimitedListToStringArray((String) entry.getValue());
for (String factoryImplementationName : factoryImplementationNames) {
result.computeIfAbsent(factoryTypeName, key -> new ArrayList<>())
.add(factoryImplementationName.trim());
}
}
}