hoipolloi
hoipolloi

Reputation: 8044

How to auto-wire constructors AND properties in Spring

The following example did not behave as expected. How can I auto-wire the constructor AND properties? I can create my Wizard bean with a robe or a wand, but not both (without explicit wiring).

Here's the code:

public static class Wizard {

    private final Robe robe;
    private Wand wand;

    public Wizard() { robe = null; }

    public Wizard(final Robe robe) { this.robe = robe; }

    public void setWand(final Wand wand) { this.wand = wand; }

    @Override
    public String toString() {
        return super.toString() + ", robe = " + robe + ", wand = " + wand;
    }
}

public static class Wand { }

public static class Robe { }

Here are my common bean definitions:

<bean id="robe" class="org.hoipolloi.Foo.Robe" />
<bean id="wand" class="org.hoipolloi.Foo.Wand" />

Now, if I configure wizard as such:

<bean id="wizard" class="org.hoipolloi.Foo.Wizard" autowire="byType" />

The robe is never populated:

// Prints org.hoipolloi.Foo$Wizard@7c7e7c7e, robe = null, wand = org.hoipolloi.Foo$Wand@72887288
System.out.println(ctx.getBean("wizard"));

If I switch to auto-wiring by constructor:

<bean id="wizard" class="org.hoipolloi.Foo.Wizard" autowire="constructor" />

Then my wizard has no wand:

// Prints org.hoipolloi.Foo$Wizard@18381838, robe = org.hoipolloi.Foo$Robe@2cec2cec, wand = null
System.out.println(ctx.getBean("wizard"));

Is there any way of auto-wiring the wizard bean so he has both robe AND wand (i.e. both constructor args and properties are wired)?

EDIT: I should note, 'byName' behaves the same as 'byType' i.e. robe is null.

Upvotes: 1

Views: 778

Answers (1)

Bozho
Bozho

Reputation: 597016

I don't think so. Either make setters for both, or include both in the constructor.

You can also use annotations instead of automatic autowiring.

Upvotes: 1

Related Questions