1

I have a class

class A{
     private Foo foo;
     private Bar bar;
     private Baz baz;
}

Now this class has constructor that initializes foo and bar. Baz however has an DataSource field which I want o be injected with spring. The A class constructor initializes all but NOT baz. Now the A class in initialized with new.

A a = new A(Foo, Bar)

The A class has the setter. Bean

<bean id="ABean" class="com.acme.A" >
        <property name="baz">
                    <bean class="com.acme.baz">
                            <property name="dataSource" ref="mysqlDataSource">  </property> 
                    </bean>     
        </property>
    </bean> 

but i keep getting:

nested exception is java.lang.NoSuchMethodException: com.acme.A.<init>()

1. How to inject only one property per bean while the rest is initialized with constructor?

2. What other way this can be solved?

mCs
  • 167
  • 1
  • 4
  • 16
  • here's a similar question that you may want to look at; [http://stackoverflow.com/questions/18069756/is-default-constructor-required-in-spring-injection/18070366][1] [1]: http://stackoverflow.com/questions/18069756/is-default-constructor-required-in-spring-injection/18070366 – incomplete-co.de Aug 11 '13 at 11:54
  • Spring container dont manage manually created (with "new" operator) beans. If you want to inject property to A you have to declare it as bean and obtain from spring context. Maybe try to use "post-construct" method to initialize Foo and Bar http://stackoverflow.com/questions/1088550/spring-how-to-call-a-method-after-bean-initialization-is-complete It is not elegant solution but it seems that there is impossible to pass non-spring beans as parameters. – yname Aug 12 '13 at 12:31

1 Answers1

1

For arguments to the constructor use the constructor-arg xml tag and for parameters that are set using setters use the property xml tag.

For that to work you need to define setBaz() method.

Then you should use getBean() and not construct the object yourself. Let spring build it for you.

selalerer
  • 3,766
  • 2
  • 23
  • 33
  • I got `setBaz()` in `A`. Because `Foo, Bar` are dynamically and quiet complex metadata from properties file populated With Apache Commons Configuration I must do it programmatically and constructed by regular program. I do want to use Spring injection only for the `Baz` property. OT Remember getBean is good only once or twice per project. – mCs Aug 11 '13 at 12:02
  • @mCs If the Spring automatically building the object for you is not good for your situation, why don't you set the baz property yourself too? You can still read it from a configuration file if you want to. – selalerer Aug 12 '13 at 16:03