HIbernate的单例例子

本文详细解析XMLHelper类中createSAXReader方法的实现,包括如何使用DTDEntityResolver,如何处理错误和实体解析的过程。同时,通过ClassLoaderHelper类展示了如何在不同环境下注入和使用ClassLoader。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

例子一:




public final class XMLHelper {

public static final EntityResolver DEFAULT_DTD_RESOLVER = new DTDEntityResolver();

private DOMReader domReader;
private SAXReader saxReader;

/**
* @param errorHandler the sax error handler
* @param entityResolver an xml entity resolver
*
* @return Create and return a dom4j {@code SAXReader} which will append all validation errors
* to the passed error list
*/
public SAXReader createSAXReader(ErrorHandler errorHandler, EntityResolver entityResolver) {
SAXReader saxReader = resolveSAXReader();
saxReader.setEntityResolver( entityResolver );
saxReader.setErrorHandler( errorHandler );
return saxReader;
}

private SAXReader resolveSAXReader() {
if ( saxReader == null ) {
saxReader = new SAXReader();
saxReader.setMergeAdjacentText( true );
saxReader.setValidation( true );
}
return saxReader;
}




}



这里在createSAXReader方法的第一行就调用了resolveSAXReader(),
后者检查了saxReader是否为空, 如果为空, 则创建新的。
不为空则返回类的内部实例saxReader.


========================================================================

例子二:

package org.hibernate.internal.util;

/**
* This exists purely to allow custom ClassLoaders to be injected and used
* prior to ServiceRegistry and ClassLoadingService existence. This should be
* replaced in Hibernate 5.
*
* @author Brett Meyer
*/
public class ClassLoaderHelper {

public static ClassLoader overridenClassLoader = null;

public static ClassLoader getContextClassLoader() {
return overridenClassLoader != null ?
overridenClassLoader : Thread.currentThread().getContextClassLoader();
}
}


这里通过thread获取了Context classloader
官方api如下:

Returns the context ClassLoader for this Thread. The context ClassLoader is provided by the creator of the thread for use by code running in this thread when loading classes and resources. If not set, the default is the ClassLoader context of the parent Thread. The context ClassLoader of the primordial thread is typically set to the class loader used to load the application.

If a security manager is present, and the invoker's class loader is not null and is not the same as or an ancestor of the context class loader, then this method invokes the security manager's checkPermission method with a RuntimePermission("getClassLoader") permission to verify that retrieval of the context class loader is permitted.

Returns:
the context ClassLoader for this Thread, or null indicating the system class loader (or, failing that, the bootstrap class loader)
Throws:
SecurityException - if the current thread cannot get the context ClassLoader
Since:
1.2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值