Spring IOC 2,使用JAVA代码配置bean

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

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值