Java如何通过构造函数注入bean?

以下示例演示了如何通过其构造函数注入bean。为此,我们将创建几个接口和类。首先,我们将创建Singer接口和Instrument接口。该Singer接口定义了一个方法调用sing(),它将使实现能够演唱一首歌曲。

第二个接口Instrument还定义了一个方法调用play()。这种方法将允许实现演奏一些乐器。定义示例接口后,我们将为每个接口创建一个实现。该类称为AnySinger和Piano。

到目前为止,这里是我们必须编写的代码:

package org.nhooo.example.spring.singer;

public interface Singer {
    /**
     * Sing a song.
     */
    void sing();
}
package org.nhooo.example.spring.singer;

public interface Instrument {
    /**
     * Play an instrument.
     */
    void play();
}
package org.nhooo.example.spring.singer;

public class AnySinger implements Singer {
    private String song = "Nana nana nana";
    private Instrument instrument = null;

    public AnySinger() {
    }

    /**
     * A constructor to create singer to sing a specific song.
     *
     * @param song the song title to sing.
     */
    public AnySinger(String song) {
        this.song = song;
    }

    /**
     * A constructor to create singer to sing a song while playing
     * an instrument.
     *
     * @param song the song title to sing.
     * @param instrument the instrument to play.
     */
    public AnySinger(String song, Instrument instrument) {
        this.song = song;
        this.instrument = instrument;
    }

    @Override
    public void sing() {
        System.out.println("Singing " + song);
        if (instrument != null) {
            instrument.play();
        }
    }
}
package org.nhooo.example.spring.singer;

public class Piano implements Instrument {

    @Override
    public void play() {
        System.out.println("Playing the Piano");
    }
}

我们创建了程序正常运行所需的类。下一步是创建我们的spring配置文件。这将在spring容器中配置我们的bean,并连接bean所需的所有依赖关系。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="piano"/>

    <bean id="singer">
        <constructor-arg value="Dust in The Wind"/>
        <constructor-arg ref="piano"/>
    </bean>

</beans>

在spring配置中,我们声明了两个bean。第一个bean是pianobean,它是一种工具。我们的示例的主要对象是singerbean。为了创建歌手,我们使用构造函数注入器注入一些值或对象引用供bean使用。

在singerBean中,我们使用&lt;constructor-arg/&gt;元素为对象注入依赖关系。该value属性可用于传递字符串或其他原始值。要传递对象引用,我们需要使用ref属性。

最后,我们将创建一个简单的程序来运行构建的spring应用程序。该代码将包括加载弹簧容器,从容器中获取bean的过程。让我们看看我们的歌手在行动。

package org.nhooo.example.spring.singer;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SingerDemo {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("singer.xml");

        Singer singer = (Singer) context.getBean("singer");
        singer.sing();
    }
}