> For the complete documentation index, see [llms.txt](https://potoyang.gitbook.io/spring-in-action-v4/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://potoyang.gitbook.io/spring-in-action-v4/di-2-zhang-zhuang-pei-bean/untitled/2.2.5-yan-zheng-zi-dong-zhuang-pei.md).

# 2.2.5　验证自动装配

现在，我们已经在 CDPlaye r的构造器中添加了 @Autowired 注解， Spring 将把一个可分配给 CompactDisc 类型的 bean 自动注入进来。为了验证这一点，让我们修改一下 CDPlayerTest，使其能够借助 CDPlayer bean 播放 CD：

{% code title="CDPlayerTest.java" %}

```java
package soundsystem;

import static org.junit.Assert.*;

import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.StandardOutputStreamLog;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=CDPlayerConfig.class)
public class CDPlayerTest {

  @Rule
  public final StandardOutputStreamLog log = new StandardOutputStreamLog();

  @Autowired
  private MediaPlayer player;
  
  @Autowired
  private CompactDisc cd;
  
  @Test
  public void cdShouldNotBeNull() {
    assertNotNull(cd);
  }

  @Test
  public void play() {
    player.play();
    assertEquals(
        "Playing Sgt. Pepper's Lonely Hearts Club Band by The Beatles\n", 
        log.getLog());
  }

}
```

{% endcode %}

现在，除了注入 CompactDisc，我们还将 CDPlayerbean 注入到测试代码的 player 成员变量之中（它是更为通用的 MediaPlayer 类 型）。在 play() 测试方法中，我们可以调用 CDPlayer 的 play() 方法，并断言它的行为与你的预期一致。

在测试代码中使用 System.out.println() 是稍微有点棘手的事情。因此，该样例中使用了 StandardOutputStreamLog，这是来源于 [System Rules 库](http://stefanbirkner.github.io/systemrules/index.html) 的一个 JUnit 规则，该规则能够基于控制台的输出编写断言。在这里，我们断言 SgtPeppers.play() 方法的输出被发送到了控制台上。

现在，你已经了解了组件扫描和自动装配的基础知识，在第 3 章中，当我们介绍如何处理自动装配的歧义性时，还会继续研究组件扫描。

但是现在，我们先将组件扫描和自动装配放在一边，看一下在 Spring 中如何显式地装配 bean，首先从通过 Java 代码编写配置开始。
