简体   繁体   中英

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 (ie both constructor args and properties are wired)?

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

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.

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