我可以仅自动装配构造函数注入的多个参数之一吗?

发布于 2024-12-21 05:15:46 字数 944 浏览 3 评论 0原文

我有一个 bean,我想向其中注入一组资源

org.springframework.core.io.Resource[]

实际上,InputStreamSource 数组就足够了。我希望我的 bean 定义看起来像:

<bean id="..." class="com.usta.SomeClass">
    <constructor-arg value="classpath:somedir/*.xml"/>
</bean>

我的构造函数在哪里:

public SomeClass(InputStreamSource[] sources);

因为那行不通,我不情愿地选择了

public SomeClass(InputStreamSource[] sources, ResourcePatternResolver resolver);

但现在我如何注入 ApplicationContext (这是一个 ResourcePatternResolver )通过构造函数注入到这个bean中?或者我可以说只自动连接这个构造函数参数吗?

我知道 Setter 注入(使用 ResourceLoaderAware)可以解决这个问题,但我尽可能坚持使用构造函数注入。

SomeClass 使用 Resources 预先进行一些初始化;使用setter注入,我将不得不推迟初始化,并且无法声明一些SomeClass的字段final

I have a bean, into which I wanted to inject an array of Resources.

org.springframework.core.io.Resource[]

Actually, an array of InputStreamSource was good enough. I wanted my bean definition to look something like:

<bean id="..." class="com.usta.SomeClass">
    <constructor-arg value="classpath:somedir/*.xml"/>
</bean>

where my constructor was:

public SomeClass(InputStreamSource[] sources);

Since that wouldn't work, I reluctantly chose to have

public SomeClass(InputStreamSource[] sources, ResourcePatternResolver resolver);

But now how can I inject the ApplicationContext (which is a ResourcePatternResolver) into this bean via constructor injection? Or can I say only auto-wire this constructor argument?

I know Setter Injection (with ResourceLoaderAware) would solve this but I am sticking to Consructor Injections as far as possible.

SomeClass uses the Resources some initialization up front; with setter injection I will have to defer initialization and not be able to declare a number of SomeClass's fields final.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

山人契 2024-12-28 05:15:46

这应该适合你......

构造函数:

public SomeClass(final Resource[] resources) { ... }

配置:

<bean id="patternResolver" class="org.springframework.core.io.support.PathMatchingResourcePatternResolver" />

<bean id="..." class="com.usta.SomeClass">
    <constructor-arg value="#{patternResolver.getResources('somedir/*.xml')}" />
</bean>

This should work for you ...

Constructor:

public SomeClass(final Resource[] resources) { ... }

Configuration:

<bean id="patternResolver" class="org.springframework.core.io.support.PathMatchingResourcePatternResolver" />

<bean id="..." class="com.usta.SomeClass">
    <constructor-arg value="#{patternResolver.getResources('somedir/*.xml')}" />
</bean>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文