spring注解 di 和 ioc 注解

注解:

   1、注解就是为了说明java中的某一个部分的作用(Type)

   2、注解都可以用于哪个部门是@Target注解起的作用

   3、注解可以标注在ElementType枚举类所指定的位置上

   4、

         @Documented    //该注解是否出现在帮助文档中

         @Retention(RetentionPolicy.RUNTIME) //该注解在java,class和运行时都起作用

         @Target(ElementType.ANNOTATION_TYPE)//该注解只能用于注解上

         public @interface Target {

             ElementType[] value();

         }

   5、用来解析注解的类成为注解解析器

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

类扫描的注解:

   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:component-scan base-package="cn.itcast.annotation.scan"></context:component-scan>

       1、 该注解解析器包含了两个功能:依赖注入和类扫描

       2、在base-package包及子包下查找所有的类

  3、如果一个类上加了@Component注解,就会进行如下的法则

        如果其value属性的值为""

              @Component

              public class Person {}

              ==

              <bean id="person" class="..Person">

       如果其value属性的值不为""

              @Component("p")

              public class Person {}

              ==

              <bean id="p" class="..Person">

  4、按照@Resource的法则再次进行操作

xml与注解:

   1、xml书写麻烦,但是效率高

   2、注解书写简单,但是效率低

@Resource(name="aa")

==下面是spring提供的注解,上面是jdk提供的注解

@Autowired

@Qualifier(name="aa")

依赖注入

@Resource

@Autowired      

@Qualifier

类扫描

@Component

@Controller

@Repository

@Service

原文地址:https://www.cnblogs.com/friends-wf/p/3826887.html