Spring IOC有三种实现方式:注解、java装配、xml。
我已经在上一篇博客中总结了注解方式笔记,注解是一种自动装配的方式,它有使用的限制场景:比如你想调用第三方库中的组件放到自己的应用中,但你是无法添加@Component。可以通过config类中配置@Bean来直接获取普通的类,这样就可以通过配置类来直接获取POJO。主要讲下java装配方式的实现。
java装配顾名思义就是通过普通的java类实现bean装配,它主要通过@Bean返回对象,而不是靠@Component。
代码思路
1、定义一个CD接口;用一个唱片CD类实现,用@Component标记为可以注入的bean
2、定义一个媒体播放接口MediaPlayer,以及它的实现类CdPlayer,该类中注入CD,并实现方法play调用CD的方法
3、定义javaconfig配置类,用@Bean放在方法前获取CD类(调用构造方法)对象(默认单例)、获取实现类CdPlayer对象(调用包含参数CD构造方法)
4、新建Main类,注入类CdPlayer,调用CdPlayer,调用play方法目的是为测试依赖(唱片)是否装配成功
1.1
public interface CD {
public void play();
}
public class FantacyByZhou implements CD{
@Override
public void play() {
// TODO Auto-generated method stub
System.out.println("周杰伦的新专辑《叶惠美》");
}
}
2.1
public interface MediaPlayer {
public void play();
}
public class CDPlayer implements MediaPlayer{
private CD cd;
public CDPlayer(CD cd) {
// TODO Auto-generated constructor stub
this.cd=cd;
}
@Override
public void play() {
// TODO Auto-generated method stub
cd.play();
}
}
3.1
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class CdPlayerJavaConfig {
@Bean
public CD cd() {
return new FantacyByZhou();
}
@Bean(name="cdplayer")
public CDPlayer cdplayer(CD cd) {
return new CDPlayer(cd());
}
}
4.1
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainjavaConfig {
public static void main(String []args){
ApplicationContext ac = new AnnotationConfigApplicationContext(CdPlayerJavaConfig.class);
CDPlayer player= (CDPlayer) ac.getBean("cdplayer");
player.play();
}
}