zoukankan      html  css  js  c++  java
  • 10_注解02_类扫描注解

    【工程截图】

    【Student.java】

    package com.HigginCui.annotation;
    
    import org.springframework.stereotype.Component;
    
    @Component("student") //相当于<bean id="student" class="......Student"></bean>
    public class Student {
        
        public void sayHello(){
            System.out.println("Student say: hello!!");
        }
    }

    【Person.java】

    package com.HigginCui.annotation;
    
    import javax.annotation.Resource;
    import org.springframework.stereotype.Component;
    
    @Component("person")  //相当于<bean id="person" class="......Person"></bean>
    public class Person {
        @Resource(name="student")
        private Student student;
        
        public void sayHello(){
            this.student.sayHello();
        }
    }

    【applicationContext.xml】

    <?xml version= "1.0" encoding ="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
            xmlns:context="http://www.springframework.org/schema/context"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           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">
    
        <!-- 把一个类放入到Spring容器中,该类就是一个component,此时不需要声明对应的bean -->
        <context:component-scan base-package="com.HigginCui.annotation"></context:component-scan>
    </beans>

    【testPerson.java】

    public class testPerson {
        @Test
        public void test(){
            ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
            Person person=(Person) context.getBean("person");
            person.sayHello();
        }
    }

    【运行结果】

    Student say: hello!!

    【注意】

    如果类上方只有@Component,那么其相当于<bean id="类名首字母小写,其他不变" class="........类名"></bean>

    【流程分析】

    1.启动Spring容器

    2.Spring容器解析类扫描的注解解析器,在base-package指定的包及子类中查找所有的类

    3.查看哪些类上面是否包含@Component注解

    4.如果该注解的value的属性为空(即:@Component),则把类名的第一个字母小写,作为id值,放入到Spring容器中

    5.如果该注解的value的属性不为空(即:@Component("person")),则用value属性的值作为id值,放入到Spring容器中

    6.再次查找在Spring容器中的类的所有属性,按照@Resource的规则给属性赋值

    【小结】

    使用了类扫描机制对的做法,配置文件更加简洁了,但是效率越来越低。

  • 相关阅读:
    有关linux查看的命令 及本机yum创建
    linux系统命令1
    手机百度网盘加群方法
    百度网盘保存超限解决办法
    c#委托、泛型委托和匿名方法
    值类型和引用类型的总结
    SQL数据查询语句(一)
    c# Invoke和Begininvoke区别
    c#public、private、protected、internal、protected internal修饰符及访问权限
    C#之打印乘法表
  • 原文地址:https://www.cnblogs.com/HigginCui/p/5574559.html
Copyright © 2011-2022 走看看