Spring装配Bean之组件扫描和自动装配

来源:互联网 发布:mac安装什么虚拟机 编辑:程序博客网 时间:2024/04/29 00:46

Spring从两个角度来实现自动化装配:

  • 组件扫描:Spring会自动发现应用上下文中所创建的bean。
  • 自动装配:Spring自动满足bean之间的依赖。

案例:音响系统的组件。首先为CD创建CompactDisc接口及实现类,Spring会发现它并将其创建为一个bean。然后,会创建一个CDPlayer类,让Spring发现它,并将CompactDisc bean注入进来。

创建CompactDisc接口:

package soundsystem;public interface CompactDisc {  void play();}

实现CompactDisc接口:

package soundsystem;import org.springframework.stereotype.Component;@Componentpublic class SgtPeppers implements CompactDisc {  private String title = "Sgt. Pepper's Lonely Hearts Club Band";    private String artist = "The Beatles";    public void play() {    System.out.println("Playing " + title + " by " + artist);  } }

在SgtPeppers类上使用了 @Component注解,这个注解表明该类会作为组件类,并告知Spring要为这个类创建bean,不需要显示配置SgtPeppers bean。
不过组件扫描默认是不开启的。我们需要显示配置一下Spring,从而命令Spring去寻找带有 @Component注解的类,并创建bean。

显示配置Spring包括Java和XML两种方式,通过Java启用组件扫描:

package soundsystem;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;@Configuration@ComponentScanpublic class CDPlayerConfig { }

注意,类CDPlayerConfig通过Java代码定义了Spring的装配规则,但是可以看出并没有显示地声明任何bean,只不过它使用了 @ComponentScan注解,这个注解能够在Spring中启用组件扫描。
如果没有其他配置的话,@ComponentScan默认会扫描与配置类相同的包。因为CDPlayerConfig位于sound system包中,因此Spring默认将会扫描这个包以及这个包下的所有子包,查找所有带有 @Component注解的类。这样的话,SgtPeppers类就会被自动创建一个bean。

通过XML启用组件扫描

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans";  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";  xmlns:context="http://www.springframework.org/schema/context";  xmlns:c="http://www.springframework.org/schema/c";  xmlns:p="http://www.springframework.org/schema/p";  xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd">;  <context:component-scan base-package="soundsystem" /></beans>

测试组件扫描能够发现CompactDisc:

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();