文章11 | 阅读 5689 | 点赞0
配置工厂ConfigurationFactory是用于加载用户的配置文件的,配置文件是怎么获取的?这篇文章就是讲的通过ConfigurationFactory去获取配置文件的过程。
private static ConfigurationFactory configFactory = new Factory();
private static class Factory extends ConfigurationFactory {
//省略部分代码
}
在getInstance方法中进行初始化,双检锁模式保证只被初始化一次
private static volatile List<ConfigurationFactory> factories = null;
private static final Lock LOCK = new ReentrantLock();
public static ConfigurationFactory getInstance() {
if (factories == null) {
LOCK.lock();
try {
if (factories == null) {
//省略部分代码以说明双检锁模式
}
} finally {
LOCK.unlock();
}
}
return configFactory;
}
final String factoryClass = PropertiesUtil.getProperties().getStringProperty(CONFIGURATION_FACTORY_PROPERTY);
if (factoryClass != null) {
addFactory(list, factoryClass);
}
//获取插件
//CATEGORY的值为ConfiguratioFactory
final PluginManager manager = new PluginManager(CATEGORY);
manager.collectPlugins();
final Map<String, PluginType<?>> plugins = manager.getPlugins();
//对内置加载的类进行类型检查并加入到未排序列表
final List<Class<? extends ConfigurationFactory>> ordered = new ArrayList<>(plugins.size());
for (final PluginType<?> type : plugins.values()) {
try {
ordered.add(type.getPluginClass().asSubclass(ConfigurationFactory.class));
} catch (final Exception ex) {
LOGGER.warn("Unable to add class {}", type.getPluginClass(), ex);
}
}
//按照OrderComparator定义的顺序进行加载
Collections.sort(ordered, OrderComparator.getInstance());
for (final Class<? extends ConfigurationFactory> clazz : ordered) {
addFactory(list, clazz);
}
//转变成unmodified的list
factories = Collections.unmodifiableList(list);
说明:
public int compare(final Class<?> lhs, final Class<?> rhs) {
final Order lhsOrder = Objects.requireNonNull(lhs, "lhs").getAnnotation(Order.class);
final Order rhsOrder = Objects.requireNonNull(rhs, "rhs").getAnnotation(Order.class);
if (lhsOrder == null && rhsOrder == null) {
return 0;
}
//有@Order注解的优先级高
if (rhsOrder == null) {
return -1;
}
//有@Order注解的优先级高
if (lhsOrder == null) {
return 1;
}
//@Order注解的值越大,优先级越高
return Integer.signum(rhsOrder.value() - lhsOrder.value());
}
举个例子:
JsonConfigurationFacotory的Order值是6,YamlConfigurationFactory的Order值是7,那么YamlConfigurationFactory应该排在JsonConfigurationFacotory之前。内置一共四个解析插件,他们的排序是:
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/sweetyi/article/details/104965981
内容来源于网络,如有侵权,请联系作者删除!