tags:

views:

462

answers:

2

How can i configure java.xml.transform.Transformer in spring framework ? I need instance of transformer to transform xml to text via xslt. Hence it is critical that the configured transformer should have knowledge of xslt stylesheet. I am not using this in a web project, rather i am using this in a standalone java program.

+1  A: 

You're going to need to get an instance of a Transformer from an appropriate TransformerFactory. You can use the built-in xerces transformer factory or a 3rd party XSLT processor, like saxonica.

Using Spring's IoC you can configure a Xerces XML transformer like this:

<bean id="transformerFactory" class="org.apache.xerces.jaxp.SAXParserFactoryImpl" />

or a saxon XML transformer like this:

<bean id="transformerFactory" class="net.sf.saxon.TransformerFactoryImpl" />

Once you have a TransformerFactory you can use dependency injection to get a new instance of a transformer either inside your bean or using the IoC. Switching to be inside your class you might have some property, say transFact that you need to set:

<bean id="myBean" class="myClass">
   <property name="transFact" ref="transformerFactory" />
</bean>

Then in your class:

public class myClass {
    // ...

    private javax.xml.transformer.TransformerFactory transFact;


    public void myMethod(){
      StreamSource transformerStream = new StreamSource(getResourceAsStream(pathToXslt));
      javax.xml.transformer.Transformer myTrans = transFact.newTransformer(transformerStream);
      // now you've got a myTrans
    }

    // ...

    public setTransFact(javax.xml.transformer.TransformerFactory transFact){
      this.transFact = transFact;
    }
}

Alternatively you can get a new transformer within IoC using the factory-method with a little more effort.

Mark E
A: 

Well, the Java to configure a Transformer is like this:

Source stylesheetSource = new StreamSource(new File("/path/to/my/stylesheet.xslt"));
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer(stylesheetSource);

If you really want to do this purely in Spring XML, this is the equivalent:

<bean id="stylesheetSource" class="javax.xml.transform.stream.StreamSource">
    <property name="systemId" value="/path/to/my/stylesheet.xslt"/>
</bean>

<bean id="transformerFactory" class="javax.xml.transform.TransformerFactory" factory-method="newInstance"/>

<bean id="transformer" factory-bean="transformerFactory" factory-method="newTransformer">
    <constructor-arg ref="stylesheetSource"/>
</bean>
skaffman
Thanks for reply. I was wondering why spring couldnt provide a bit more support so that all i need to do is pass name of my xslt and it should locate it on the classpath and build configure the transformer. Also , i believe i might need to set some properties on the transformer
Jimm