Spring 裝配Bean 基於註解

2021-08-02 00:26:06 字數 1582 閱讀 2316

註解:就是乙個類,使用@註解名稱

開發中:使用註解 取代 xml配置檔案

註解使用前提,新增命名空間,讓spring掃瞄含有註解類

在xml檔案中加這段**讓其掃瞄類中的所有註解

1.@component 把普通pojo例項化到spring容器中,用來取代< bean class=」」 >

@component(「id」) 用來取代< bean id=」」 class=」」 >

2.web開發,提供3個@component註解衍生註解(功能一樣,名字不一樣)取代< bean class=」」 >

@repository :dao層,功能與 @component 相同

@service:service層,功能與 @component 相同

@controller:web層,功能與 @component 相同

3.依賴注入 ,給私有字段設定,也可以給setter方法設定

普通值:@value(「」)

引用值:

方式1:按照【型別】注入   @autowired

方式2:按照【名稱】注入1   @autowired

@qualifier(「名稱」)

方式3:按照【名稱】注入2   @resource(「名稱」)

@autowired這個註解就是spring可以自動幫你把bean裡面引用的物件的setter/getter方法省略,它會自動幫你set/get。

class="com.service.userservice">

name="userdao"

ref bean="userdao">property>

property>

id="userdao"

class="com.service.userdao"/>

這樣你在userservice裡面要做乙個userdao的setter/getter方法。

但如果你用了@autowired的話,你只需要在userservice的實現類中宣告即可。

public
class userservice

id="userservice"

class="com.service.userservice">

bean>

id="userdao"

class="com.dao.userdao"/>

bean>

4.生命週期

初始化:@postconstruct

銷毀: @predestroy

5.作用域

@scope(「prototype」)  多例

spring框架的核心時spring容器。容器負責管理應用中元件的生命週期,它會建立這些元件並保證它們的以來能夠得到滿足,這樣的話,元件菜呢個完成預定的任務。

Spring 裝配Bean 基於註解

註解 就是乙個類,使用 註解名稱 開發中 使用註解 取代 xml配置檔案。component取代 component id 取代 2.web開發,提供3個 component註解衍生註解 功能一樣 取代 repository dao層 service service層 controller web層...

Spring 裝配bean基於註解

裝配bean基於註解 一 用註解取代 xml 配置檔案 component component id 取代 bean id class web開發中,提供3個 component註解衍生註解 功能一樣 取代 bean class 依賴注入,給私有字段設定,也可以給setter方法設定 生命週期 初始...

Spring 裝配Bean 基於註解

1.component取代 component id 取代 2.web開發,提供3個 component註解衍生註解 功能一樣 取代 repository dao層 service service層 controller web層 3.依賴注入 給私有字段設定,也可以給setter方法設定 普通值 ...