Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I would like to know whether its possible to use both constructor and setter injection while configuring spring bean?

share|improve this question

closed as off-topic by gnat, MichaelT, Kilian Foth, Bart van Ingen Schenau, Dan Pichelman Nov 1 '13 at 16:28

  • This question does not appear to be about software development within the scope defined in the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

This question appears to be off-topic because it is about implementation issues (see help center) - belongs to Stack Overflow but is too old to migrate –  gnat Oct 31 '13 at 12:09
add comment

2 Answers

Seems that in old version of Spring mixing of constructor-arg and property are not supported:


But in Spring 3.x it unofficially works (I didn't find example of mixing in official docs).

UPDATE My colleague discover:

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

on same sources with:

<bean class="service.MenuService">
    <constructor-arg index="0" type="java.lang.String" value="#{user}"/>
    <constructor-arg index="1" type="java.lang.String" value="#{password}"/>
    <constructor-arg index="2" type="java.lang.String" value="#{uri}"/>
    <property name="system" value="OPRT"/>
    <property name="client" value="OPRT"/>

while there are only one 3-args constructor in bean. My host, test and production services have no such error.

The reason to use constructor - it perform some additional actions on non-Spring library by invoking init() method. And set args as fields.

So I change spring-beans.xml to:

<bean class="service.MenuService" init-method="init">
    <property name="login" value="#{user}"/>
    <property name="password" value="#{password}"/>
    <property name="httpsUrl" value="#{uri}"/>
    <property name="system" value="OPRT" />
    <property name="client" value="OPRT" />

and error go way for problematic setup. Take attention to init-method= part.

share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.