Spring註解開發搭配xml

2021-10-21 02:21:38 字數 1965 閱讀 4228

元件掃瞄目的,一下把乙個包裡面所有的類都掃瞄到我們的主配置檔案裡面,就不用乙個乙個的bean了很實用

元件掃瞄**

<

context:component-scan

base-package

="com.zhiyou100"

/>

掃瞄之後把該報下所有的類都掃瞄一遍,再遇到下面的註解,有就表明把該類掃瞄到spring空間裡面,沒有對應的註解,那就不掃瞄到這裡面

@component (對應pojo層) 寫在對應的實體類上面 這個類就交給spring容器了

@service(對應service層) 寫在service對應的實現類上面,這個類就交給了spring容器管理了

@controller(對應web層) 寫在web包下的類上面,這個累就交給spring容器管理了

@repository(對應dao層) 寫在dao層介面的實現類上面,這個類就交給spring容器管理了

以上四個註解,如果沒有寫別名,別名就預設為類名首字母小寫 寫了別名就按照別名引用,這樣就不用再xml裡面乙個乙個的bean物件了

註解引入類

//這是dao層裡面的類,使用註解@repository

@repository

("userdao"

)//這就是指定類別名

public

class

userdaoimpl

implements

userdao

主要是,寫在類的上面,

@scope

(scopename =

"singleton"

)//表示通過屬性scopename屬性 singleton指定單例模式

public

class

user

implements

serializable

@scope

(scopename =

"singlent"

)//表示通過屬性scopename屬性 prototype 在多例模式下建立物件

public

class

user

implements

serializable

單例模式下: 返回都是同乙個物件

多例模式,每次返回的都是新物件

**簡單型別 包含 基本資料型別 + string字串型別 **

@value 簡單型別的注入屬性值

引用型別:就是引用屬性上面加入註解

//純@autowires屬性注入

// 關聯dao層 屬性注入

@autowired

//如果其他地方有很多的userdao物件,那麼這裡就可能會出現混亂

private userdao userdao;

// @autowired + @qualifier 同時使用

// 新增car對映

@autowired

@qualifier

("c1"

)//這裡就是因為有很多的car物件 @autowired會出現混亂 所以使用 @qualifier("c1") 指定物件,避免造成混亂

@resource

(name =

"car"

)private car car;

//@resource 使用

// 關聯service層 屬性注入

@resource

(name =

"userservice"

)//直接指定物件

private userservice userservice;

Spring註解開發

spring註解開發 dao層用的註解 repository service層的註解 service controller表現層的註解 controller 以上的三個註解都是用 componment新增三個衍生的註解 屬性依賴注入 value的屬性注入 value wwtmy love 注入的是屬...

spring註解開發

第一步,設定xml約束檔案 第一步,設定xml約束檔案 xmlns xsi xmlns context xsi schemalocation spring beans.xsd spring context.xsd 第二步,定義bean 除了 component外,spring提供了3個功能基本和 c...

Spring註解開發

在spring4之後,要使用註解開發,但是必須保證aop的包存在 使用註解必須保證匯入context約束增加註解的支援 xmlns xmlns xsi xmlns context xsi schemalocation spring beans.xsd spring context.xsd conte...