java Spring:将资源作为 InputStream 注入到工厂方法中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3626279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:42:51  来源:igfitidea点击:

Spring: Injecting Resource as InputStream into a factory-method

javaspring

提问by nebenmir

I want to use anti-samy from OWASP. They got a Policy object, that is instantiated via a factory method.

我想使用来自 OWASP 的 anti-samy。他们得到了一个 Policy 对象,它是通过工厂方法实例化的。

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.

需要传递给工厂方法的 InputStream 表示策略对象的配置文件。

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?

是否可以在 spring xml 上下文配置中使用创建策略 bean?我知道,有一个 Resource 对象,可以从类路径加载文件。但是我需要的是从那个 Resource 对象中创建一个 InputStream 。我可以直接在 xml-spring-context 中这样做吗?或者我是否需要编写java代码才能获得InputStream?

回答by Sean Patrick Floyd

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.

将工厂方法方法与构造函数参数(将映射到工厂方法参数)一起使用,并从资源符号自动转换为 InputStream。

<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:

请参阅Spring 参考的以下部分:

回答by skaffman

@seanizer's solution would be a good one if Policyclosed the InputStreamafter 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.

@seanizer 的解决方案如果在完成阅读后Policy关闭InputStream它会是一个很好的解决方案,但显然它没有。这将导致泄漏,泄漏的严重程度取决于调用的频率以及资源的性质。

To be safe, you should consider writing a custom FactoryBeanimplementationinstead, which handles the opening and closing of the InputStreamsafely. The FactoryBeanwould be injected with a Resourceobject.

为了安全起见,您应该考虑编写一个自定义FactoryBean实现,它可以InputStream安全地处理打开和关闭。该FactoryBean会与被注入Resource对象。