隐式的bean发现与自动装配机制

时间:2023-03-09 05:34:33
隐式的bean发现与自动装配机制

使用beans.xml文件进行bean的创建和注入通常是可行的,但在便利性上Spring提供了更简单的方法——自动装配

接下来我们假设一个场景:我有若干播放器(MediaPlayer{CD播放器/MP3}),我也有很多媒体文件例如(CompactDisc{CD光盘/MP3文件})。
现在,我们需要创建两个接口MediaPlayer/CompactDisc,然后创建他们的实现CDPlayer/CompactDisc_zhoujielun。注意:CompactDisc_zhoujielun是周杰伦的CD光盘。代码如下:
 package com.spring.cd;

 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; @Component//Spring自动创建bean
public class CDPlayer implements MediaPlayer{
private CompactDisc cd; @Autowired//表明Spring初始化后尽可能地去满足bean的依赖,在这里它注入了一个CompactDisc的对象
public CDPlayer(CompactDisc cd){
this.cd=cd;
}
@Override
public void player() {
System.out.println("wo yong CD!");
}
}

当然,我们也可以在创建bean时对它命名,在CDPlayer类中可以体会到。代码如下:

package com.spring.cd;

import org.springframework.stereotype.Component;

@Component("ZhouJieLun")
public class CompactDisc_zhoujielun implements CompactDisc{
private String title="发如雪";
private String artist="周杰伦"; @Override
public void play(){
System.out.println("播放:"+title+"来自艺术家:"+artist);
}
}
接下来,我们需要启用组件扫描,组件扫描过程是通过Java代码来定义Spring的装配规则。代码如下:
package com.spring.cd;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@ComponentScan("com.spring.cd") //参数代表当前需要扫描的路径,为空默认为当前包路径
@Configuration("cd")//需要扫描的包名称
//通过java代码定义spring的装配机制
public class CDPlayerConfig { }

 值得注意的是,真正的实现过程与代码主体非常复杂,@Component,@ComponScan,@Autowired,@Comfiguration等注解的使用方法与参数是多样的。

为了实现可视化,我们新建一个JUnit4测试。代码如下:
package com.spring.cd;

import static org.junit.Assert.*;
import org.junit.Test;
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;
@Autowired
private MediaPlayer player;
@Test
public void test() {
player.player();
cd.play();
assertNotNull(cd);
assertNotNull(player);
} }
上下文创建成功。

热爱分享拒绝拿来主义,博客精神永存——cvrigo

    2016-11-09 00:19:44