概述:
创建应用对象之间协作关系的行为通常称为装配(wiring),这也是依赖注入(DI)的本质。在本章我们将介绍使用Spring装配 bean的基础知识。因为DI是Spring的最基本要素,所以在开发基于Spring的应用时,你随时都在使用这些技术。
2.1Spring配置的可选方案
主要装配方式:
- 在XML中进行显示配置
- 在java中进行显式配置
- 隐式的bean发现机制和自动装配
2.2 自动化装配bean
Spring从两个角度实现自动化装配:
- 组件扫描(component scanning)
- 自动装配(autowiring)
本书的例子CD盘插入CD播放器
package learn.chapter2;
/**
* 定义一个CD接口
* @author chenliang
*
*/
public interface CompactDisc {
void play();
}
package learn.chapter2;
import org.springframework.stereotype.Component;
/**
* 创建一个Adele的歌曲hello
* @author Administrator
*
*/
@Component
public class AdeleSong implements CompactDisc{
private String title = "hello";
private String artist = "Adele";
public void play() {
System.out.println("歌曲为:" + title + "\t歌手为:" + artist);
}
}
java配置类形式
package learn.chapter2;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration //说明是一个配置类
@ComponentScan //表示的它的作用是扫描
public class CDPlayerConfig {
}
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"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="learn.chapter2"/>
</beans>
测试类:
package learn.chapter;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import learn.chapter2.CDPlayerConfig;
import learn.chapter2.CompactDisc;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=CDPlayerConfig.class)
public class CDPlayer {
@Autowired
private CompactDisc cd;
/**
* 基于java配置文件注入
*/
@Test
public void cdShouldNotBeNullByConfig() {
assertNotNull(cd);
}
/**
* 基于配置文件自动注入
* 注释@RunWith和@ComtextConfiguration
*/
@Test
public void cdShouldNotBeNullByXml() {
//首先要加载xml配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("scan.xml");
assertNotNull(ac.getBean("adeleSong"));
}
}
总结:
1.java配置需要两个注释,第一个@Configuration (表明它不是一个普通的类) 第二个@ComponentScan (既然不是一个普通类,那它做啥,扫描@Component)
2.JUnit测试@RunWith基于Spring的运行测试器,@ContextConfiguration 可以加载java类的配置(在特定的环境下加载配置java的配置文件)
3.@ComponentScan 可以设置基础包 @ComponentScan(basePackages="learn.chapter2") 多个目录的时候,类似java数组一样配置
@ComponentScan(basePackages={"基础包1","基础包2"}) 或者 @ComponentScan(basePackageClasses={CDPlayer.class, DVDPlayer.class})