1. 程式人生 > >Spring 使用註解完成bean例項化、依賴注入的相關配置以及注意事項

Spring 使用註解完成bean例項化、依賴注入的相關配置以及注意事項

一、 相關配置例項化註解介紹
首先使用註解完成spring容器例項的配置,主要用到以下幾個:
1、@Repository(“name”):配置持久層例項bean,通常用在DAO; 這裡配置的name屬性相當於在
2、@Service(“”):業務層bean例項化,也即Service層相關類
3、@Controller(“”) :控制層bean例項,如:struts中的action
4、@Scope(“”):指定bean例項化的模式,常用屬性,單例(singleton),多例(prototype);另外,還有session,request
5、@Component(“”):用於人任意類的例項化配置,不如上邊幾種有那麼強的語義。
2. 依賴注入相關注解
1、@Autowired:為依賴屬性實現注入依賴例項,但是存在以一種情況使用該標籤會出錯——當一個容器中,存在多個同類型單例模式的bean例項

,autowrired會因無法確定應該注入哪個例項而報錯類似於:expected single matching bean but found 3 。

下面舉個簡單的例子:

下面程式碼為兩個有依賴關係且要例項化的bean

@Controller("customerAction")
public class CustomerAction extends ActionSupport {
    @Autowired    //指定屬性依賴注入物件
    //@Qualifier("customerService1")
    private CustomerService customerService; 

    //.......
} ///////////////////////////////////////////////////// @Service public class CustomerServiceImpl implements CustomerService { //........ }

此時,在spring中人為的配置瞭如下bean例項

<bean id="customerService1" class="cn.ppppp.crm.service.impl.CustomerServiceImpl"> <!-- 這裡配置為單例 -->
    </bean>
    <bean id="customerService2" class="cn.ppppp.crm.service.impl.CustomerServiceImpl"
>
<!-- 這裡配置為單例 --> </bean>

2、@Qualifier(“customerService1”):配合Autowired使用,如Action中被註釋語句,解決上述問題,屬性指定需要用哪個例項來注入依賴屬性。附,另一種解決方法:以上面例子,當指定@Service(“customerService”)的name屬性時也不會出現以上錯誤。我的理解是,框架在載入的時候在沒有指定例項化bean物件,首先載入由註解完成的例項。
二、使用的註解完成bean例項化的環境配置(注:STS IDE)
1、新增jar包:spring-aop-4.2.4.RELEASE.jar

2、Spring容器applicationContext.xml:

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

</beans>

同時在做以下配置window>preferences>xml catalog>
這裡寫圖片描述
location:為本地xsd檔案路徑
容器掃描元件,完成對註解的載入

<!-- 
        掃描@Reposotory,@Service,@Controler,@Scope註解
        base-package: 指定掃描範圍,即base-package目錄下子包,或檔案
     -->
    <context:component-scan base-package="cn.pppp.crm"></context:component-scan>
    <!-- 對依賴屬性注入使用註解 -->
    <context:annotation-config></context:annotation-config>