前言
在前文(https://blog.csdn.net/qq_43576028/article/details/104714918)中,我们学习了基于注解(Annotation)的方式去配置bean,自动配置有2个核心组成部分:
1.ComponentScan——组建扫描
2.Autowired——自动装配
接下来介绍Spring装配bean的另一种方式——基于JavaConfig的显示装配。
为什么
既然有了这么方便的自动装配bean的方式,为什么还要用JavaConfig呢。这是因为有时候,项目中的组建是来自第三方库的,在这种情况下是没有办法在类上添加@Component和@Autowired注解的,所以需要JavaConfig
前期准备
以声音系统(Sound System)为例,我们创建一个CD类接口、CD播放机类接口、继承CD接口实例化一张唱片、继承CD播放机类接口实例化一台CD播放机,然后检测能否达到依赖注入(DI)的效果。
CD类接口:CompactDisc.java
package soundsystem;
public interface CompactDisc {
void play();
}
CD播放器类接口:MediaPlayer.java
package soundsystem;
public interface MediaPlayer {
void play();
}
实例化一张CD:彭羚——《如梦初醒》SgtPeppers.java
package soundsystem;
public class SgtPeppers implements CompactDisc {
private String title="入门初醒";
private String artist="彭羚";
public void play() {
System.out.println("Playing " + title + " by " + artist);
}
}
实例化一台CD播放机:CDplayer.java,利用@AutoWired自动装配一张cd
package soundsystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class CDPlayer implements MediaPlayer {
private CompactDisc cd;
@Autowired()
public CDPlayer(CompactDisc cd) {
this.cd = cd;
}
public void play() {
cd.play();
}
}
显示配置JavaConfig
对CD播放器进行配置,编写CDPlayerConfig.java,使用@Bean对刚才的那张唱片进行显示配置,这里的bean会自动返回一张唱片。事实上,不一定要返回彭羚的《如梦初醒》,我们可以自己把握,根据自己的喜好决定返回哪张唱片,甚至随机返回。
package soundsystem;
import org.springframework.context.annotation.Bean;
public class CDPlayerConfig {
@Bean
public CompactDisc sgtPeppers(){
return new SgtPeppers();
}
}
测试
利用Sping的测试功能,观察是否成功达到依赖注入:
编写测试类CDPlayerTest.java:
package soundsystem;
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 {
@Autowired
private CompactDisc cd;
@Test
public void cdShouldNotBeNull(){
cd.play();
}
}
测试结果:正在播放 彭羚的 如梦初醒