Spring中的@Resource注解执行过程

首先,我们先写一个简单的例子,这样看起来更清楚一点:

1. 写两个类Student和Person类

Student类

public class Student {
	public void say() {
		System.out.println("This is a student!");
	}
}

Person类

import javax.annotation.Resource;

public class Person {
	@Resource(name="student")
	Student student;
	public void sayPerson() {
		this.student.say();
	}
}


2. ApplicationContext.xml配置


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.2.xsd">
      
      <bean id="student" class="spring_ioc_05_di_annotation.Student"></bean>
      <bean id="person" class="spring_ioc_05_di_annotation.Person"></bean>
     <context:annotation-config/>
     
</beans>

3. 测试类


public class AnnotationTest {
	/**
	 * 执行过程:
	 * 1.启动加载spring容器
	 * 2.将Spring容器中的bean实例化(Person,student)
	 * 3.当spring容器执行到解析配置文件处时
	 * 			<context:annotation-config/>
	 *		spring容器会在纳入spring管理的bean的范围内查找哪些类的属性上是否加有@Resource注解
	 * 4.如果在属性上找到@Resource注解
	 *		如果@Resource的注解name属性为""
	 *			则把@Resource所在的属性的名称和Spring容器中的id作匹配
	 *				如果匹配成功,则赋值
	 *				如果匹配不成功,则会按照类型进行配置
	 *					如果匹配成功,则赋值;匹配不成功,报错
	 *		如果@Resource的注解的name的值不为""
	 *			则解析@Resource注解name属性的值,把值和spring容器中的ID进行呢匹配
	 *				如果匹配成功,则赋值
	 *				如果匹配不成功,则报错
	 *
	 *	说明:
	 *		注解代码越来越简单,效率越来越低
	 */
	@Test
	public void TestPerson() {
		ApplicationContext context = 
				new ClassPathXmlApplicationContext("applicationContext.xml");
		Person person = (Person) context.getBean("person");
		person.sayPerson();
	}
}




  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值