Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: Injecting Resource as InputStream into a factory-method

Tags:

java

spring

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?

like image 289
nebenmir Avatar asked Sep 02 '10 10:09

nebenmir


2 Answers

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:

  • Instantiation with a static factory method
  • Built-in Property Editors (InputStreamEditor is relevant here)
  • Examples of Dependency Injection (last section is about constructor-arg used in the context of a static factory-method)
like image 75
Sean Patrick Floyd Avatar answered Nov 15 '22 02:11

Sean Patrick Floyd


@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.

like image 4
skaffman Avatar answered Nov 15 '22 02:11

skaffman