前言
spring2.5以后支持注解来注入实体之间的依赖关系,主要有以下两种注解配置的方式,下面着重说明这两种方式的区别与联系。
使用示例
方式一
public class ConfigService {
private IConfigDao configDao = null; //按类型进行匹配
}
public class ConfigService {
"configDao") (
private IConfigDao configDao = null; //和Qualifier注解配套使用,按名称进行匹配
}方式二
@Service
public class ConfigService {
@Resource
private IConfigDao configDao = null; //默认按变量名称进行匹配
}
区别说明
区别一:@Autowired:是Spring提供的一个注解
@Resource:是J2EE原生的注解
区别二:@Autowired:是按类型进行匹配的,如果要通过名称进行匹配则必须配合@Qualifier注解一起使用。
默认如果没有匹配到则抛出异常,当然也可以设置@Autowired(required=false)来标明不需要强制匹配,这样即使匹配不到也不会报错。
@Resource:
情况1:name未指定,type未指定
默认按字段名称进行匹配,如果没有匹配到则按字段类型进行匹配,都没有匹配到则抛出异常;
情况2:name指定,type未指定
按指定的name名称进行匹配,如果没有匹配到则抛出异常;
情况3:name未指定,type指定
按指定的type类型进行匹配,如果没有匹配到或匹配到多个则抛出异常;
情况4:name指定,type指定
按指定name名称且指定type类型进行匹配,如果没有匹配到则抛出异常;
@Resource源码解读
下面只是贴出了@Resource注解两比较重要个属性的源码解释: ({TYPE, FIELD, METHOD})
(RUNTIME)
public Resource {
/**
* The JNDI name of the resource. For field annotations,
* the default is the field name. For method annotations,
* the default is the JavaBeans property name corresponding
* to the method. For class annotations, there is no default
* and this must be specified.
*/
String name() default "";
/**
* The Java type of the resource. For field annotations,
* the default is the type of the field. For method annotations,
* the default is the type of the JavaBeans property.
* For class annotations, there is no default and this must be
* specified.
*/
Class<?> type() default java.lang.Object.class;
.....
}
通过源码分析得知:@Resource注解
- 当标记field字段时,name的默认值是字段名称,type的默认值是字段的类型;
- 当标记method方法时,name的默认值是javabean setter方法对应的属性名称,type的默认值是javabean setter方法对应的属性类型;
- 当标记class类时,name和type是没有默认值的,必须手动指定;
总结
推荐使用@Resource注解,这个注解是属于J2EE的,减少了与Spring的耦合,这样代码看起就比较优雅 。