问题:
我正在与其他团队编写的库集成。该库提供了我在 Spring 驱动的应用程序中使用的一组类。我的应用程序中的每个 bean 都在单例范围内。
此外,该库中 99% 的类都使用构造函数注入(inject)。
我正在使用 XML,我的配置看起来与以下内容非常相似:
<bean id="lib.service1" class="lib.Service1"/>
<bean id="lib.service2" class="lib.Service2">
<constructor-arg ref="lib.service1"/>
</bean>
<bean id="lib.service3" class="lib.Service3">
<constructor-arg ref="lib.service1"/>
</bean>
<bean id="lib.service4" class="lib.Service3">
<constructor-arg ref="lib.service2"/>
<constructor-arg ref="lib.service3"/>
</bean>
<!-- other bean definitions -->
<bean id="lib.serviceN" class="lib.ServiceN">
<constructor-arg ref="lib.serviceX"/>
<constructor-arg ref="lib.serviceY"/>
<constructor-arg ref="lib.serviceZ"/>
<constructor-arg ref="lib.serviceK"/>
</bean>
<!-- other bean definitions -->
我想要什么:
我想简化我的配置,不使用bean ID,并要求spring根据bean构造函数中的参数类型为我进行构造函数注入(inject)。我还可以要求库实现者向类构造函数添加 @Inject 注释(99% 的类只有一个公共(public)构造函数),但这就是我可以要求对其库进行重构的全部内容。
最终我想在我的 spring 配置中遵循以下内容(不起作用,但说明了这个想法):
<bean class="lib.Service1"/>
<bean class="lib.Service2"/>
<bean class="lib.Service3"/>
<!-- ... -->
<bean class="lib.ServiceN"/>
在这里,我期望 Spring 弄清楚我想对所有这些 bean 使用构造函数注入(inject),并根据构造函数参数类型推断 bean 实例。
请注意,我无法使用组件扫描 - 它们有一个包(上面给出的示例中的 lib.),并且该包中的某些类对我的应用程序来说毫无用处,而且成本太高,无法不必要地创建。另外,我没有使用的一些类是实验性的,可以更改/重命名/删除,恕不另行通知。
最佳答案
添加 autowire="constructor"
,假设这些 bean 类型只有一个构造函数,并且相应的参数与单个 bean 匹配。
<bean class="lib.Service1" autowire="constructor"/>
来自文档
"constructor"
Analogous to
"byType"
for constructor arguments. If there is not exactly one bean of the constructor argument type in the bean factory, a fatal error is raised. Note that explicit dependencies, i.e."property"
and"constructor-arg"
elements, always override autowiring. Note: This attribute will not be inherited by child bean definitions. Hence, it needs to be specified per concrete bean definition.
关于java - 如何告诉 Spring 在不提供构造函数参数的情况下实例化选定的 bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28488407/