Spring IOC容器Bean管理 三

2022-06-21 04:24:11 字數 2844 閱讀 9412

ioc 操作 bean 管理(基於註解方式)

​ 1、什麼是註解

​ (1)註解是**特殊標記,格式:@註解名稱(屬性名稱=屬性值, 屬性名稱=屬性值…)

​ (2)使用註解,註解作用在類上面,方法上面,屬性上面

​ (3)使用註解目的:簡化 xml 配置

​ 2、spring 針對 bean 管理中建立物件提供註解

​ 下面四個註解功能是一樣的,都可以用來建立 bean 例項

​ (1)@component

​ (2)@service

​ (3)@controller

​ (4)@repository

3、基於註解方式實現物件建立

​ 第一步 引入依賴 (引入spring-aop jar包)

​ 第二步 開啟元件掃瞄

<

context:component-scan

base-package

="com.atguigu"

>

context:component-scan

>

第三步 建立類,在類上面新增建立物件註解

//在註解裡面 value 屬性值可以省略不寫,

//預設值是類名稱,首字母小寫

//userservice -- userservice

@component(value = "userservice") //註解等同於xml配置檔案:

<

bean

id="userservice"

class

=".."

/>

public class userservice

}

4、開啟元件掃瞄細節配置

<

context:component-scan

base-package

="com.atguigu"

use-defaultfilters

="false"

>

<

context:include-filter

type

="annotation"

expression

="org.springframework.stereotype.controller"

/>

context:component-scan

>

<

context:component-scan

base-package

="com.atguigu"

>

<

context:exclude-filter

type

="annotation"

expression

="org.springframework.stereotype.controller"

/>

context:component-scan

>

5、基於註解方式實現屬性注入

(1)@autowired:根據屬性型別進行自動裝配

​ 第一步 把 service 和 dao 物件建立,在 service 和 dao 類新增建立物件註解

第二步 在 service 注入 dao 物件,在 service 類新增 dao 型別屬性,在屬性上面使用註解

@service

public

class

userservice }//

dao實現類

@repository

//@repository(value = "userdaoimpl1")

public

class userdaoimpl implements

userdao

}

(2)@qualifier:根據名稱進行注入,這個@qualifier 註解的使用,和上面@autowired 一起使用

//

定義 dao 型別屬性

//不需要新增 set 方法

//新增注入屬性註解

@autowired //

根據型別進行注入

//根據名稱進行注入(目的在於區別同一介面下有多個實現類,根據型別就無法選擇,從而出錯!)

@qualifier(value = "userdaoimpl1")

private

userdao userdao;

.csdn.net/weixin_45496190/article/details/107071204

//

@resource

//根據型別進行注入

@resource(name = "userdaoimpl1") //

根據名稱進行注入

private userdao userdao;

(4)@value:注入普通型別屬性

@value(value = "abc")

private string name

6、完全註解開發

(1)建立配置類,替代 xml 配置檔案

@configuration //

作為配置類,替代 xml 配置檔案

@componentscan(basepackages = )

public

class

springconfig

(2)編寫測試類

@test

public

void

testservice2()

SpringIOC核心容器bean

spring ioc是為了將類解耦 建立乙個類 public class helloworld public helloworld public void hello 通過xml檔案配置bean物件 xmlns xmlns xsi xsi schemalocation spring beans.xs...

spring IOC容器bean生命週期

spring ioc 容器可以管理 bean 的生命週期,spring 允許在 bean 生命週期的特定點執行定製的任務.spring ioc 容器對 bean 的生命週期進行管理的過程 通過構造器或工廠方法建立 bean 例項 為 bean 的屬性設定值和對其他 bean 的引用 bean 可以使...

springIOC容器管理的bean預設都是單例的

springioc容器管理的bean預設都是單例的 我們平時使用的 controller註解標註的控制器 service標註的介面等 預設都是單例的 那麼也就是說,我們定義乙個成員變數,執行緒之間可以共用!滑稽!幹了幾年了我竟然不知道。先模擬個鎖玩一下 測試spring 管理的bean 的作用域 鎖...