SWS-586 - specify custom TransformerFactory in org.springframework.xml.transform.TransformerObjectSupport

This commit is contained in:
Arjen Poutsma
2010-01-06 14:26:05 +00:00
parent b900c0c810
commit 9fd6a22f4d

View File

@@ -22,10 +22,13 @@ import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
/**
* Convenient base class for objects that use a <code>Transformer</code>. Subclasses can call {@link
* #createTransformer()} or {@link #transform(Source, Result)}. This should be done per thread (i.e. per incoming
@@ -40,10 +43,48 @@ public abstract class TransformerObjectSupport {
/** Logger available to subclasses. */
protected final Log logger = LogFactory.getLog(getClass());
private static TransformerFactory transformerFactory = TransformerFactory.newInstance();
private TransformerFactory transformerFactory;
private Class transformerFactoryClass;
/**
* Specify the {@code TransformerFactory} class to use.
*/
public void setTransformerFactoryClass(Class transformerFactoryClass) {
Assert.isAssignable(TransformerFactory.class, transformerFactoryClass);
this.transformerFactoryClass = transformerFactoryClass;
}
/**
* Instantiate a new TransformerFactory.
* <p>The default implementation simply calls {@link TransformerFactory#newInstance()}.
* If a {@link #setTransformerFactoryClass "transformerFactoryClass"} has been specified explicitly,
* the default constructor of the specified class will be called instead.
* <p>Can be overridden in subclasses.
* @param transformerFactoryClass the specified factory class (if any)
* @return the new TransactionFactory instance
* @see #setTransformerFactoryClass
* @see #getTransformerFactory()
*/
protected TransformerFactory newTransformerFactory(Class transformerFactoryClass) {
if (transformerFactoryClass != null) {
try {
return (TransformerFactory) transformerFactoryClass.newInstance();
}
catch (Exception ex) {
throw new TransformerFactoryConfigurationError(ex, "Could not instantiate TransformerFactory");
}
}
else {
return TransformerFactory.newInstance();
}
}
/** Returns the <code>TransformerFactory</code>. */
protected TransformerFactory getTransformerFactory() {
if (transformerFactory == null) {
transformerFactory = newTransformerFactory(transformerFactoryClass);
}
return transformerFactory;
}
@@ -55,7 +96,7 @@ public abstract class TransformerObjectSupport {
* if thrown by JAXP methods
*/
protected final Transformer createTransformer() throws TransformerConfigurationException {
return transformerFactory.newTransformer();
return getTransformerFactory().newTransformer();
}
/**