首页 > 代码库 > Spring 自动化装配Bean

Spring 自动化装配Bean

声明一张cd的接口:

public interface CompactDisc {
    public abstract void play();
}

实现cd接口:

@Component("SgtPeppers")
public class SgtPeppers implements CompactDisc {
    private String title = "Sgt.Pepper‘s Lonely Hearts Club Band";
    private String artist = "The Beatles";

    @Override
    public void play() {
        System.out.println("playing" + title + " by " + artist);
    }
}

声明cdplayer:

@Component("CDplayer")//表明该类作为组件类,没必要显示的配置Bean实例,括号内为组件名
public class CDPlayer {
    /*
    * @Autowired注解可以用在构造器上,也可以用在set方法上,也能直接放在下列代码所示地方
    * spring会满足有该注解的依赖,如果只有一个bean匹配依赖需求的话,这个bean就会被装配进来
@Autowired 默认按类型装配 *
*/ @Autowired private CompactDisc cd; public CompactDisc getCd() { return cd; } public void setCd(CompactDisc cd) { this.cd = cd; } public void play(){ cd.play(); } }

测试类:

public class CDPlayerTest {
    public static void main(String[] args) {
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        CDPlayer cdPlayer= (CDPlayer) context.getBean("CDplayer");
        cdPlayer.play();
    }
}

xml:自动扫描包,寻找有注解的类

 <context:component-scan base-package="com.xue.soundsystem"></context:component-scan>

总结:@Component:相当于xml的bean中添加其实例,括号内为id。@Autowired会按类型寻找匹配的实例进行匹配。@Resource可以按照名字进行装配。

Spring 自动化装配Bean