I want to use anti-samy from OWASP. They got a Policy object, that is instantiated via a factory method.
public static Policy getInstance(InputStream inputStream);
The InputStream that needs to be passed to the factory-method represents the config file for the policy-object.
Is it possible to use create a policy bean in an spring xml context config? I know, that there is a Resource object, that can load files from classpath. But what I need is to make a InputStream out of that Resource object. Can I doe this directly in the xml-spring-context? Or do I need to write java code in order to get the InputStream?
Use the factory-method approach together with a constructor-arg (that will be mapped to a factory method argument) and automatically converted to an InputStream from a resource notation.
<bean id="policy" class="org.owasp.validator.html.Policy"
factory-method="getInstance">
<!-- type needed because there is also a getInstance(String) method -->
<constructor-arg
value="classpath:path/to/policyFile.xml"
type="java.io.InputStream" />
</bean>
See the following parts of the Spring Reference:
constructor-arg
used in the context of a static factory-method
)@seanizer's solution would be a good one if Policy
closed the InputStream
after it was finished reading from it, but apparently it doesn't. This will result in a leak, the severity of which depends how often it is called, and the nature of the resource.
To be safe, you should consider writing a custom FactoryBean
implementation instead, which handles the opening and closing of the InputStream
safely. The FactoryBean
would be injected with a Resource
object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With