Spring学习笔记(二)-@Resource注解的使用规则

@Resource注解的使用规则:

   1、在spring的配置文件中导入命名空间

         xmlns:context="http://www.springframework.org/schema/context"

         http://www.springframework.org/schema/context

         http://www.springframework.org/schema/context/spring-context-2.5.xsd

   2、引入注解解析器

        <context:annotation-config></context:annotation-config>

   3、在spring的配置文件中把bean引入进来

   4、在一个类的属性上加

            @Resource(name="student_annotation")

            private Student student;

         从该注解本身

               @Target({TYPE, FIELD, METHOD})

               @Retention(RUNTIME)

               public @interface Resource {

                  String name() default "";

               }

           1、该注解可以用于属性上或者方法上,但是一般用户属性上

           2、该注解有一个属性name,默认值为""

   5、分析整个过程:

        1、当启动spring容器的时候,spring容器加载了配置文件

        2、在spring配置文件中,只要遇到bean的配置,就会为该bean创建对象

        3、在纳入spring容器的范围内查找所有的bean,看哪些bean的属性或者方法上加有@Resource

        4、找到@Resource注解以后,判断该注解name的属性是否为""(name没有写)

              如果没有写name属性,则会让属性的名称的值和spring中ID的值做匹配,如果匹配成功则赋值

                                        如果匹配不成功,则会按照类型进行匹配,如果匹配不成功,则报错

              如果有name属性,则会按照name属性的值和spring的bean中ID进行匹配,匹配成功,则赋值,不成功则报错

posted @ 2016-11-28 13:57  To哥  阅读(756)  评论(0编辑  收藏  举报