Bean配置方案并不仅一种,三种装配方式可以并没有使spring的Bean装配变得麻烦,使用者可以根据自己的喜好使用,也可以混合使用!
三种装配方式:
1、在XML中进行显示配置
2、在Java中进行显示配置
3、隐式的Bean发现机制和自动装配
这里建议使用自动装配!
需要的jar包:http://download.csdn.net/download/fancheng614/10118789
一、自动装配Bean:
打个比方:DVD唱机和CD之间的关系,如果只有DVD而没有CD,显然DVD并没有任何价值了,只有将CD注入到DVD唱机中,DVD才能实现它的价值!
先来定义一个CD:
package com.mfc.autobean;
/**
* 2017年11月14日20:40:41
* 自动装配的CD接口
* */
public interface CompactDisc {
public void play();
}
CD的实现类:
package com.mfc.autobean;
import org.springframework.stereotype.Component;
/**
* 2017年11月14日20:42:13
* 我的CD实现了CD的接口
* 这里可以使用@Name代替@Component
* */
@Component("compactDisc")
public class MyCompactDisc implements CompactDisc {
@Override
public void play() {
System.out.println("CD播放器播放了我的CD");
}
}
唱机接口:
package com.mfc.autobean;
/**
* 2017年11月14日21:42:23
* 唱机的接口
* */
public interface MediaPlayer {
public void play();
}
唱机实现:
@Autowired也可以用在set方法上或者构造器上
package com.mfc.autobean;
import javax.inject.Inject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 2017年11月14日21:43:26
* 对唱片接口进行实现
* */
@Component
public class CDPlayer implements MediaPlayer {
/**
* 这里的@Autowired可以和@Inject互换
* */
private CompactDisc compactDisc;
@Inject
public CDPlayer(CompactDisc compactDisc){
this.compactDisc = compactDisc;
}
@Override
public void play() {
cd.play();
}
}
启用组件扫描:
package com.mfc.autobean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* 2017-11-14 20:44:21
* 启用组件扫描(默认组件扫描是关闭的),这里在java类中启用组件扫描,
* 也可以再xml中启用组件扫描:<context component-scan="包名"/>
* 配置多个包:@ComponentScan(basePackages = {"com.mfc.autobean","com.mfc.dao"})
* */
@Configuration
@ComponentScan("com.mfc.autobean")
public class CDPlayerConfig {
}
测试类:
package com.mfc.autobean;
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.test.context.C