从Spring2.5版本开始,Spring开始支持使用注解自动装配Bean的属性。使用注解自动装配与XML中使用autowire属性没有太大区别。但是使用注解,可以针对 Bean的某一个属性使用自动装配,而XML中的autowire属性只能针对某一个类。所以 使用注解方式允许更细颗粒的自动装配。
下面介绍使用的方法
我们先定义一个 乐器类
public class Instrument {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void play(){
System.out.println("play "+name);
}
}
定义了一个 表演者的接口,在定义一个音乐家的类并实现表演者接口
public interface Performer {
public void perform();
}
public class Musician implements Performer{
private Instrument instrument;
public Instrument getInstruments() {
return instrument;
}
public void setInstrument(Instrument instrument) {
this.instrument = instrume