spring in action 学习笔记(九)使用注解进行装配

来源:互联网 发布:mac抹掉磁盘 编辑:程序博客网 时间:2024/06/05 17:19

从spring 2.5开始,支持使用注解来自动装配bean的属性,使用注解自动装配与xml中使用autowire属性自动装配并没有太大差别。

但是使用注解方式允许更细粒度的自动装配,我们可以选择性地标注某一个属性来对其应用自动装配。

其实,简单点,就是配置更简单了,更一目乐然了。

spring容器默认是禁用注解装配。所以基于注解进行自动装配,要先开启配置

 <context:annotation-config/>

在配置文件中,这样配置就好了,同时引入了这个context的命名空间,前面已经介绍了,spring的核心包提供了十个命名空间

实现基于注解的自动装配,有三种注解

1. spring自带的@Autowired注解

2. JSR-330的@Inject注解

3. JSR-250的@Resource注解

我们暂时学习使用@Autowired来演示使用注解的方式进行自动装配

    <bean id="instrument" class="com.springinaction.ch03.Saxophone"/>    <bean id="Instrumentalist" class="com.springinaction.ch03.Instrumentalist">        <property name="song" value="heal the world" />    </bean>
首先,还是之前的那个类,我们给String 类型的song 注入了一个heal the world歌名,但是配置文件中没有注入instrument,所以这个instumentalist中的instrument是空的。

    @Autowired    public void setInstrument(Instrument instrument) {        this.instrument = instrument;    }

使用注解进行装配,只需要在setInstrument方法上标注这个注解即可。