解释:所谓装配就是把一个类需要的组件给它设置进去,英文就是wire,wiring;注解Autowire也叫自动装配。
目前Spring提供了三种配置方案:
- 在XML中进行显式的配置
- 在Java中进行显式的配置
- 隐式的bean发现机制和自动装配
就我个人而言,用XML和自动装配混搭最多,用Java代码进行装配用的最少,几乎不用。这三种配置方案提供的功能会有重叠,大部分都可以根据个人喜好来选择。Spring的配置风格是可以相互搭配的,三种方式可以共存。
三者的适用范围:
XML > JavaConfig > 注解
自动化装配bean
自动化装配最为便利,写的东西最少,用起来很快。要实现自动化装配可以从两个方面来看:
组件扫描(component scanning):Spring会自动发现应用上下文中所创建的bean
自动装配(autowiring):Spring自动满足bean之间的依赖
具体的步骤可以用下图来描述:
创建可被发现的bean
这里用CD播放器来先演示依赖注入(Dependency Inject)。
涉及到的类图如下:
CompactDisc接口
1 package soundsystem; 2 3 public interface CompactDisc { 4 void play(); 5 }
CompactDisk接口的实现类:SgtPeppers
1 package soundsystem; 2 3 import org.springframework.stereotype.Component; 4 5 @Component 6 public class SgtPeppers implements CompactDisc { 7 8 private String title = "Sgt. Pepper's Lonely Hearts Club Band"; 9 private String artist = "The Beatles"; 10 11 public void play() { 12 System.out.println("Playing " + title + " by " + artist); 13 } 14 }
开启组件扫描的Java配置类:CDPlayerConfig
1 package soundsystem; 2 3 import org.springframework.context.annotation.ComponentScan; 4 import org.springframework.context.annotation.Configuration; 5 6 @Configuration 7 @ComponentScan 8 public class CDPlayerConfig { 9 }
测试类:CDPlayerConfig
1 package soundsystem; 2 3 import org.junit.Test; 4 import org.junit.runner.RunWith; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.test.context.ContextConfiguration; 7 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 8 import org.springframework.util.Assert; 9 10 @RunWith(SpringJUnit4ClassRunner.class) 11 @ContextConfiguration(classes=CDPlayerConfig.class) 12 public class CDPlayerTest { 13 14 @Autowired 15 private CompactDisc cd; 16 17 @Test 18 public void cdShouldNotBeNull() { 19 Assert.notNull(cd, "inject failed"); 20 } 21 }
只需简单几步即可实现依赖注入,很强大。
解释说明:
给SgtPeppers用了@Component这个注解后,Spring会为这个类去创建bean。
组件扫描默认是不启用的,需要显式的配置Spring让其去寻找带有@Component注解的类,并为其创建bean。
开启组件扫描的任务是CDPlayerConfig来实现的,通过Java代码定义了Spring的装配规则。
如果没有其他的配置,@ComponentScan默认扫描与配置类相同的包。
@CDPlayerConfig类位于soundsystem包中,Spring将会扫描这个包和这个包下的所有子包。
如果用XML来开启组件扫描的话,可以使用<context:component-scan>元素:<context:component-scan base-package="soundsystem" />
测试类中用到了两个注解:SpringJUnit4ClassRunner会在测试的时候自动创建Spring的应用上下文,@ContextConfiguration会告诉它需要在CDPlayerConfig类中加载配置,然后类CDPlayerConfig中包含了@ComponentScan,所以上下文中会包含CompactDisc的bean。