spring in action 学习笔记(九)使用注解进行装配
2017-10-16 12:59
561 查看
从spring 2.5开始,支持使用注解来自动装配bean的属性,使用注解自动装配与xml中使用autowire属性自动装配并没有太大差别。
但是使用注解方式允许更细粒度的自动装配,我们可以选择性地标注某一个属性来对其应用自动装配。
其实,简单点,就是配置更简单了,更一目乐然了。
spring容器默认是禁用注解装配。所以基于注解进行自动装配,要先开启配置
在配置文件中,这样配置就好了,同时引入了这个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方法上标注这个注解即可。
但是使用注解方式允许更细粒度的自动装配,我们可以选择性地标注某一个属性来对其应用自动装配。
其实,简单点,就是配置更简单了,更一目乐然了。
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方法上标注这个注解即可。
相关文章推荐
- Spring in Action 学习笔记—第二章装配Bean
- SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-004-消除BEAN自动装配的歧义@QUALIFIER及自定义注解
- Spring学习笔记--使用注解装配
- spring in action 学习笔记(八)自动装配
- spring学习笔记7--使用spring进行面向切面的(AOP)编程(1)注解方式实现
- SpringInAction 学习笔记:自动装配歧义性处理
- SpringInAction 学习笔记:高级装配
- Spring in Action 学习笔记一
- spring学习笔记(12)——使用注解方式配置bean
- Spring 注解方式进行事务管理的用法介绍详解【Java学习笔记】
- ITCAST视频-Spring学习笔记(用@Resource注解完成属性装配)
- Spring in Action 学习笔记—第五章事务管理
- Spring in Action 学习笔记—第六章远程调用
- ITCAST视频-Spring学习笔记(使用构造器装配属性)
- Spring in Action 第一部分学习笔记
- 学习笔记: Struts2中使用validate框架对Action的不同方法进行验证
- Spring in Action 第二部分学习笔记
- Spring in Action 学习笔记—第七章访问企业服务
- Spring in Action 学习笔记—第三章创建切面
- 学习笔记-----Spring_MVC注解的使用