spring 使用註解注入bean
阿新 • • 發佈:2018-11-09
學了兩種使用註解注入bean的方式,按照網上提供的方法學習並整理的。
1、@Resource 2、@Autowired
首先要說明的是 spring的標頭檔案,下面是一個比較全的標頭檔案
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
第一種使用介紹:
@Resource 預設是按照名稱來裝配注入的,只有當找不到與名稱匹配的bean才會按照型別來裝配注入;是由J2EE提供,可以減少系統對spring的依賴,建議使用 ,可以書寫標註在欄位或者該欄位的setter方法之上。
bean配置:
<context:annotation-config />
<bean id="helloAction" class="com.hsx.struts.action.HelloAction" scope="prototype"></bean> <bean id="userService" class="com.hsx.struts.service.UserService" scope="prototype"> <!-- <property name="sqlMapClient"> <ref bean="sqlMapClient"/> </property> --> </bean>
Java程式碼配置
a、標註在欄位上
@Resource(name="userService")
private UserService userService;
b、標註在setter方法上
@Resource(name="userService")
public void setUserService(UserService userService) {
this.userService = userService;
}
說明:括號內 name="userService" 可以省去,系統會自動按照屬性名尋找bean.如果配了name屬性,系統會按照name所配的bean id 查詢。放在 欄位上時,set方法可以省去。
第二種使用介紹:
@Autowired:預設是按照型別裝配注入的,如果想按照名稱來轉配注入,則需要結合@Qualifier一起使用;可以書寫標註在欄位或者該欄位的setter方法之上。
bean配置:
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="helloAction" class="com.hsx.struts.action.HelloAction" scope="prototype"></bean>
<bean id="userService" class="com.hsx.struts.service.UserService" scope="prototype"></bean>
Java 程式碼配置:
@Autowired
private UserService userService;
或者:
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
按照名稱注入,bean按照上邊即可。
Java程式碼配置:
@Autowired
@Qualifier("userService")
private UserService userServices;
或者
@Autowired
public void setUserServices(@Qualifier("userService")UserService userService) {
this.userServices = userService;
}