Spring实战4 学习笔记(一)

装配Bean

1、首先创建接口:CompactDisc

package soundsystem;

public interface CompactDisc {
	void play();
}

2、创建两个类:BlankDisc和SgtPeppers

package soundsystem;


import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
@Qualifier("Blank")
public class BlankDisc implements CompactDisc {

	private String title = "Blank. Pepper's Lonely Hearts Club Band";
	private String artist = "ymc";
	
	public BlankDisc(String title) {
		
		this.title = title;
	}
	
	public void play() {
		System.out.println("【BlankDisc 】>>>>>>>>>>>>>>>>>Playing "+title+" by "+artist);
	}
}
package soundsystem;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
@Qualifier("Sgt")
public class SgtPeppers implements CompactDisc {
 
    private String title = "Sgt. Pepper's Lonely Hearts Club Band";
    private String artist = "ymc";
 
    public void play() {
        System.out.println("【SgtPeppers 】>>>>>>>>>>>>>>>>>Playing " + title + " by " + artist);
    }
}

3、创建JavaConfig来装配Bean:CDConfig,装配Bean时用到了@Bean注解,同时用@Qualifier注解来区分两个相同类型的Bean。

package soundsystem;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CDConfig {

	@Bean
	public CompactDisc SgtPeppers11() {
		return new SgtPeppers();
	}
	
	@Bean
	@Qualifier("22")
	public CompactDisc BlankDisc22() {
		return new BlankDisc("22");
	}
	
	@Bean
	@Qualifier("33")
	public CompactDisc BlankDisc33() {
		return new BlankDisc("33");
	}
}

4、测试用的类:CDPlayerTest,用@Autowired来注入Bean,同时用@Qualifier来区分注入的Bean是哪个。

package soundsystem;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CDConfig.class)
public class CDPlayerTest {
	@Autowired
	@Qualifier("22")
	private BlankDisc cd1;
	
	@Autowired
	private SgtPeppers cd2;
	
	@Autowired
	@Qualifier("33")
	private CompactDisc cd3;
			
	@Test
	public void cdShouldNotBeNull() {
		cd1.play();
		cd2.play();
		cd3.play();
	}
}

5、测试的结果:

【BlankDisc】>>>>>>>>>>>>>>>>>Playing 22 by ymc
【SgtPeppers】>>>>>>>>>>>>>>>>>Playing Sgt. Pepper's Lonely Hearts Club Band by ymc
【BlankDisc】>>>>>>>>>>>>>>>>>Playing 33 by ymc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值