1. 程式人生 > >Spring依賴注入(基於XML配置檔案和Annotation的方式完成屬性裝配)

Spring依賴注入(基於XML配置檔案和Annotation的方式完成屬性裝配)

依賴注入的方式(手工裝配):
1.使用bean的構造器注入—基於XML方式
2.使用屬性setter方法注入—基於XML方式
3.使用field注入—基於Annotation方式
注入依賴物件可採用手工裝配和自動裝配,在實際應用中建議使用手工裝配,自動裝配會產生未知情況,且無法預知裝配結果

使用構造器方式注入:

// 提供構造方法
    public PersonServiceBean(PersonDao personDao, String name) {
        this.personDao = personDao;
        this.name = name;
    }


    @Override
    public
void save() { System.out.println(name); personDao.add(); } public void destory() { System.out.println("關閉開啟的資源"); }
<!--在bean中子元素的配置如下-->
 <constructor-arg index="0" type="cn.itcast.dao.PersonDao" ref="personDao"></constructor-arg>
    <constructor-arg
index="1" value="jxlgdx">
</constructor-arg>

手工裝配依賴物件:兩種方式
1.在xml配置檔案中,通過在bean節點下的配置,程式碼如下

    <bean id="personService" class="cn.itcast.service.impl.PersonServiceBean">
        <!-- id屬性中不能有特殊字元,name屬性可以有 -->   
    <!-- 構造器注入 -->
    <constructor-arg index="0" type="cn.itcast.dao.PersonDao"
ref="personDao"/>
<constructor-arg index="1" type="String" value="jxlgdx"/> <!-- 屬性setter方法注入 --> <property name="name" value = "zhangsan"></property> </bean>

2.在java code中使用@Autowired或@Resource註解方式進行裝配(推薦使用Resource),但使用註解方式需要在xml檔案中配置如下資訊,
*
@Resource是JDK中自帶的註解,而@Autowired是Spring Framework提供的,為了方便解耦,推薦使用Resource*

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

    <context:annotation-config/>

在java程式碼上使用註解時,可以寫在欄位上也可以寫在set方法上

@Resource
    public void setPersonDao(PersonDao personDao) {
        this.personDao = personDao;
    }//寫在set方法上

public class PersonServiceBean implements PersonService {
    @Resource private PersonDao personDao;
    private String name;//寫在欄位上

Annotation:配置的作用,註解代表某一種業務意義,註解背後的處理器才有實際作用:先解析所有屬性,根據搜尋規則,如果能match上,則取得bean,通過反射技術注入

另一種註解@Autowired的使用:
[email protected]預設按照型別裝配,@Resource預設按照名稱裝配,當找不到與名稱匹配的bean才會按照型別裝配(@Resource的名稱可以通過name屬性指定,如果沒有name屬性則預設取欄位的名稱作為bean的名稱尋找依賴物件,當註解使用在setter方法上面時,預設區屬性名作為bean的名稱尋找依賴物件)

PS:@Reource,若沒有指定name屬性,並且按照預設名稱也找不到依賴物件時,註解會自動根據型別裝配,但一旦指定了name屬性後,則在只能按照名稱裝配

自動裝配(不推薦使用,會產生不可預知的結果)
例子如下,aotuwire屬性取值有多種,詳細見API文件

<bean id="xxx" class="yyy.yyy" autowire="byType"/>