tags:

views:

988

answers:

3

I want to autowire a bean partially - that is, I want some args to be autowired but other to be explicitly set. For example:

public MyClient(Service svc, boolean b)

In the case of this constructor, I would like to specify in my xml the value for b, but have svc autowired. Is that possible?

Thanks, Lowell

+3  A: 

I don't think it is possible with constructors, but with explicit setters it certainly is. Just annotate the ones you want autowired with @Autowired, and set the others in your config-file

Something like:

public MyClient() {}

@Autowired
public setService (Service svc) {...}

public setBoolean (boolean b) {...}

and then in your config

<context:annotation-config />

<bean id="service">...</bean>

<bean id="yourbean" class="MyClient">
    <property name="b" value="true"/>
</bean>
NR
NR, your example makes sense. It would be great if there was a way to do it all through the constructor, though, to make the object immutable.
lowellk
maybe you can try with a "split" solution? Autowire the service with a setter, and have a constructor with the boolean?
NR
That would be better, but I'm hopeful it can be done with just a constructor. Fingers crossed :-)
lowellk
A: 

I figured it out on my own, hooray!

The way I did it was to put something like the following in my xml:

<bean class="MyClient" autowire="constructor">
   <constructor-arg index="1">...</constructor-arg>
<bean>
lowellk
A: 

lowellk - can you elaborate? Please post the full solution. I'm trying to do the same thing.

Thanks.