Spring IOC註解的詳解

2021-08-27 08:25:55 字數 1474 閱讀 1520

一.component元件

修飾乙個類,將這個類交給spring管理

這個類有三個衍生註解(功能類似),修飾類

@controller:修飾web層

@service:修飾service層

@dao:修飾dao層

二.屬性注入的註解

1.普通屬性

@value

2,物件屬性

(1)@autowired:設定物件型別的屬性的值,是按照型別進行屬性注入的

我們習慣按照名字進行屬性注入

所以一般是autowired和qualifier一起完成按照名稱屬性注入

(2)@resource  按照名稱進行屬性注入

註解步驟:

1.在spring.xml中配置掃瞄元件

2.編寫dao層

public inte***ce haohandao
@repository("haohandao")

//相當於在spring.xml中

public class haohanimpl implements haohandao

}

3.編寫service層

public inte***ce haohanservice
這裡的@resource是屬性注入 

@service("haohanservice")

public class haohanserviceimpl implements haohanservice

}

4.測試

haohandao.add();

三.bean的其他註解

1.bean 的生命週期的註解

postconstruct:初始化註解

predestroy:銷毀方法

2.bean的作用範圍註解

@scope

singleton

prototype

request

session

globlsession

四.ioc註解和xml開發比較

1.xml和註解比較

xml可以適用於任何場景,結構清晰,方便維護

註解,當類不是自己提供的時候不能使用

2.xml和註解的整合開發

類都在xml裡寫,屬性注入用註解寫

掃瞄是為了掃瞄類上的註解,當類上沒有註解時就不掃瞄,使用屬性注入的註解

public class userdao 

}

public class userservice 

}

Spring IOC常用註解的詳解及案例

目錄 1 spring ioc常用註解的解釋 2 ioc案例 基於xml和基於註解的案例 3 spring中 configuration註解的使用 4 使用spring整合junit實現測試 參考 參考 基本 xml和註解兩個案例 案例 含有事務案例 上述 2 中基於註解開發的ioc案例中,還需要x...

Spring IOC註解開發

引入註解約束,配置元件掃瞄 類上的註解 conponent 三個衍生註解 controller web層 service service層 repository dao層 普通屬性的註解 value 物件屬性的註解 resource name 替代 autowired qualifier value...

Spring IOC通過註解配置bean

spring 能夠從 classpath 下自動掃瞄 偵測和例項化具有特定註解的元件。特定註解有 放在類上面的 controller 標識表現層元件 service 標識服務層元件 respository 標識持久層元件 component 基本註解,標識了乙個受spring管理的元件對於掃瞄到的元...