HIbernate的单例例子

例子一:

 

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

你可能感兴趣的:(java,单例,Hibernate,Singleton)