@Resource注解的使用

@Resource注解的使用

2015年01月05日 20:17:23

阅读数:15298

   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进行匹配,匹配成功,则赋值,不成功则报错

个人分类: spring

猜你喜欢

转载自blog.csdn.net/wangshuminjava/article/details/81478028
今日推荐