开发者

Spring: Injecting Resource as InputStream into a factory-method

I want to use anti-s开发者_如何学JAVAamy 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:

  • 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)


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜