1. 程式人生 > >Spring的@Resource註解及原理

Spring的@Resource註解及原理

package cn.xhx.spring.di.annotation.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.xhx.spring.di.annotation.Person;

public class AnnotationTest {
	/**
	 * 原理
	 * 	1、當啟動spring容器時,建立兩個物件(student,person)
	 * 	2、當spring容器解析到
	 * 			<context:annotation-config></context:annotation-config>
	 * 	   spring容器會在spring容器管理的bean的範圍內查詢這些類的屬性上面是否加了@Resource註解
	 * 	3、spring解析@Resource註解的name屬性
	 * 		如果name屬性為""
	 * 			說明該註解根本沒有寫name屬性
	 * 			spring容器會得到該註解所在的屬性的名稱和spring容器中的id相匹配,如果匹配成功,則賦值
	 * 																   如果匹配不成功,則按照型別進行匹配
	 * 																  還不成功,報錯!
	 * 		如果name屬性不為""
	 * 			則按照name屬性的值和spring容器中的id做匹配,如果匹配成功,則賦值,不成功,則報錯!
	 *	說明:
	 *		註解只能作用於引用型別
	 *		註解寫法比較簡單,但是效率比較低
	 *		xml寫法比較複雜,但是效率比較高
	 */
	
	@Test
	public void AnnotationTest () {
		ApplicationContext applicationContext = 
				new ClassPathXmlApplicationContext("applicationContext.xml");
		Person person = (Person)applicationContext.getBean("person");
		person.getStudent().say();//輸出"student say"
		
	}
}
package cn.xhx.spring.di.annotation;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.annotation.Resource;

public class Person {
	private String name;
	@Resource(name="student")
	/**
	 * @Autowired  //按照型別進行匹配
	 * @Qualifier("student") //按照id進行匹配
	 * @Resource是java擴充套件包下的,spring為了不使用java的註解,編寫了@Autowired和@Qualifier,其2個的作用相加等於@Resource
	 */
	private Student student;
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Student getStudent() {
		return student;
	}
	
}
package cn.xhx.spring.di.annotation;

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

<?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-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">

	<bean id="student" class="cn.xhx.spring.di.annotation.Student"></bean>
	<bean id="person" class="cn.xhx.spring.di.annotation.Person"></bean>
	
	<context:annotation-config></context:annotation-config>
</beans>