Spring_10_DI_基于注解注入

基于注解的注入,又称自动装配。

 

Spring提供的装配标签:@Autowired与@Qualifier

让Spring将属性需要的对象,从Spring容器中找出来,并注入给该属性。

 

· 配置

在测试环境中,可以不做任何配置,直接使用@Autowired。(在Spring3.0前必须配置)

非测试环境中,需进行配置:

1、新增命名空间,配置schema位置。

2、在<beans>中添加一行代码。

<context:annotation-config />

 

· 阅读源代码

@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {

	/**
	 * Declares whether the annotated dependency is required.
	 * <p>Defaults to {@code true}.
	 */
	boolean required() default true;

}

可看出,其使用目标为:构造器,字段,方法,注解。

 

· 一些细节

1、标注在构造器时,可以注入多个对象。

@Autowired
	public BeanObject(OtherBean other, OtherBean other2) {
    // do work
}

2、标注在字段(实例成员变量)时,可以不提供setter方法。

3、标注在方法时,该方法为属性的setter方法。

4、使用@Autowired标签可以注入Spring内置的重要对象。如BeanFactory,ApplicationContext。

5、默认情况下@Autowired标签必须要能找到对应的对象,否则报错。

可以配置@Aurowired的required属性值为false来避免该问题。即表示该属性不是必须的。

 

基于@Autowired注入属性的流程:

1、首先,根据依赖对象的类型找。找不到则报错,找到唯一的匹配类型,则注入。

找到多个匹配类型时,则按id、name找。

(当@Autowired标注的是接口对象时,若该接口有唯一实现,则找该实现类型。

若没有实现,则报错。若有多个实现,则按id、name查找)

 

2、按照id、name找。找不到,就报错。

可以用配置@Qualifier的value属性,根据value的值找匹配的id、name。

 

 JavaEE提供的装配标签:@Resource

· 配置

配置同@Autowired。

<context:annotation-config>既引入了@Autowired标签的解析器,也引入了@Resource的解析器。

 

· 阅读部分源代码

@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
public @interface 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 "";
    // 其余代码略
}

@Resource提供了name属性,相当于@Qualifier的name属性。

使用方法基本同@Autowried和@Qualifier。

 

@Autowired与@Resource

1、@Autowired:Spring定义的标签,所以可能不太稳定,并且对象和spring框架关联(Spring对代码有侵入);

2、@Resouce:是J2EE的规范,所以稳定,在J2EE规范容器中也能正常使用。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值