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的规则给属性赋值

【小结】

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

posted @ 2016-06-11 00:17  HigginCui  阅读(280)  评论(0编辑  收藏  举报