Spring依赖注入

  • Post author:
  • Post category:其他


内容主要来自《Spring实战》第二章,区别在于自己写了一个测试类,对于初学者更容易理解依赖注入。

先定义两个接口:

1. CompactDisc.java

package soundsystem;

public interface CompactDisc {
    void play();
}

2. MP.java  //书上用的是MediaPlayer接口

package soundsystem;

public interface MP {
    public void play();
}

再分别定义两个类来实现上面的接口:

3. SgtPeppers.java

package soundsystem;
import org.springframework.stereotype.Component;

@Component
public class SgtPeppers implements CompactDisc{

    private String title = "Sgt.Pepper's Lonely Hearts Club Bands";
    private String artist = "The Beatles";

    public void play() {
        System.out.println("Playing "+title+" by "+artist);
    }
}

4. CDPlayer.java

package soundsystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CDPlayer implements MP {

    private CompactDisc cd;

    @Autowired
    public CDPlayer(CompactDisc cd) {
        this.cd = cd;
    }

    public void play() {
        cd.play();
    }

}


定义一个配置类:


5. CDPlayerConfig.java

package soundsystem;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
public class CDPlayerConfig {

}


最后定义一个测试类用来测试


Bean


是否被成功创建且自动装配:

6.

Test.java

package soundsystem;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Test {

    public static void main(String[] args) {
        // 通过Java配置来实例化Spring容器
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(CDPlayerConfig.class);

        // 在Spring容器中获取Bean对象
        CDPlayer myPlayer = context.getBean(CDPlayer.class);

        // 调用对象中的方法
        myPlayer.play();
        // 销毁该容器
        context.destroy();
    }

}

build 并运行Test,如果看到信息:“Playing Sgt.Pepper’s Lonely Hearts Club Bands by The Beatles”,则说明组建扫描和自动装配成功完成。



版权声明:本文为bufanq原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。