1. 程式人生 > >@resource與@autowired的區別

@resource與@autowired的區別

@resource與@authorwired在本質上它們的作用是一樣的,都是省去為一個物件變數寫get,set方法,自動為這個物件注入例項化物件即注入依賴。而它們的注入的方式還是有所區別的 

@resource是基於j2ee的註解,預設是按名字進行註解,若不指定裝配bean的名字,當註解寫在欄位上時,預設取欄位名,按照名稱查詢通過set方法進行裝配,倘若有多個子類,則會報錯。若想不報錯,只需加(required=false)
例如:

package com.chexiang.common;

public class Customer 
{       @Resource
	private Person person;
	
	public Customer(Person person) {
		this.person = person;
	}
	
	public void setPerson(Person person) {
		this.person = person;
	}
	//...
}
package com.chexiang.common;
@Component
public class Person 
{
	//...
}
其對應的xml裝配過程是如下,先定義customer的bean,然後申明裝配方式是byname,再定義一個person類的bean。這是id名為customer的bean物件的物件屬性會自動按照屬性名去找尋id名與屬性名一樣的bean,則id為person的bean被注入到了customer的person變數裡
<bean id="customer" class="com.chexiang.common.Customer" autowire="byName" />	
<bean id="person" class="com.chexiang.common.Person" />
@autowired是基於spring的註解org.springframework.beans.factory.annotation.Autowired,它預設是按型別進行的裝配的,如果想要它按名字進行裝配只需在@autowired下面加@qualifier("name")`註解,其對應的xml裝配方式如下 兩個Bean,person 和 ability.
package com.chexiang.common;
 
public class Person 
{       @autowired
	private Ability ability;
	//...
}
package com.chexiang.common;
@Component 
public class Ability 
{
	private String skill;
	//...
}
<!-- person has a property type of class "ability" -->
	<bean id="person" class="com.yiibai.common.Person" autowire="byType" />
		
	<bean id="invisible" class="com.yiibai.common.Ability" >
		<property name="skill" value="Invisible" />
	</bean>
id名為person的bean會把ability屬性按照bean裡定義的class的型別進行裝配,因為id名為invisible的bean的class型別與id名為person的變數ability的型別相同,則進行裝配。