简体   繁体   中英

Overriding constructor arguments in Spring

Say I have two beans (where BeanA properties are immutable, requiring constructor injection):

<bean id="beanA1" class="BeanA">
  <constructor-arg type="ServiceA" ref="serviceA" />
  <constructor-arg type="ServiceB" ref="serviceB" />
  <constructor-arg type="ServiceC" ref="serviceC" />
  <constructor-arg type="boolean" value="false" />
</bean>

<bean id="beanA2" class="BeanA">
  <constructor-arg type="ServiceA" ref="serviceA" />
  <constructor-arg type="ServiceB" ref="serviceB" />
  <constructor-arg type="ServiceC" ref="serviceC" />
  <constructor-arg type="boolean" value="true" />
</bean>

Since they share everything but the boolean, I wanted to merge them as such:

<bean id="beanA1" class="BeanA">
  <constructor-arg type="ServiceA" ref="serviceA" />
  <constructor-arg type="ServiceB" ref="serviceB" />
  <constructor-arg type="ServiceC" ref="serviceC" />
  <constructor-arg type="boolean" value="false" />
</bean>

<bean id="beanA2" parent="beanA1">
  <constructor-arg type="boolean" value="true" />
</bean>

However, this doesn't seem to be working

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beanA2' defined in class path resource [context.xml]: Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)

Any way to do this with constructor injection?

You can't do what you are trying to achieve with the Constructor Dependency Injection because in the case of the beanA2 you are calling a constructor with a single boolean parameter.

However, you can achieve what you want if you change the injection from a constructor-based to a setter-based DI:

<bean id="beanA1" class="BeanA">
  <property type="ServiceA" ref="serviceA" />
  <property type="ServiceB" ref="serviceB" />
  <property type="ServiceC" ref="serviceC" />
  <property type="boolean" value="false" />
</bean>

<bean id="beanA2" parent="beanA1">
  <property type="boolean" value="true" />
</bean>

For further details, you can read more at the Spring documentation Bean definition inheritance

Current exception telling you that there is no constructor with only one boolean value. It is not clear why you need constructor injection, you could try just to set needed property by it name to false .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM