spring依赖注入的方式(一)

为了方便类的管理,spring提供了依赖注入的思想:类的实例化不由程序员控制,而是交给sprig容器进行管理。

spring提供了多种类型的注入方式---注解、xml注入;

1  注解注入

  有两种:@Autowired @Resource。两种都可以实现注入,但是二者的差别也很明显。

  •  @Resource 默认按照名称注入,在找不到名称的时候,会继续通过类型匹配;
  •  @Autowired 默认按照类型注入;
  •    @Resource 注解是由J2EE提供,而@Autowired是由spring提供,故为了减少系统对spring的依赖,建议使用@resource方式;
  •    二者都可以标注在字段上或者该字段的setter方法之上。

1.1  修改spring配置文件信息

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-2.5.xsd">
 <!--这是注解的声明-->
   <context:annotation-config/>
</beans

1.2  注意事项

@Autowire 默认按照类型装配,默认情况下它要求依赖对象必须存在如果允许为null,可以设置它required属性为false,如果我们想使用按照名称装配,可 以结合@Qualifier注解一起使用;
@Resource默认按照名称装配,当找不到与名称匹配的bean才会按 照类型装配,可以通过name属性指定,如果没有指定name属 性,当注解标注在字段上,即默认取字段的名称作为bean名称寻找依赖对象,当注解标注在属性的setter方法上,即默认取属性名作为bean名称寻找 依赖对象.

注意:如果没有指定name属性,并且按照默认的名称仍然找不到依赖的对象时候,会回退到按照类型装配,但一旦指定了name属性,就只能按照名称 装配了.

posted @ 2016-07-28 14:38  爬行  阅读(249)  评论(0编辑  收藏  举报