Spring 自動裝配bean學習筆記

2021-10-08 13:14:53 字數 2696 閱讀 1905

當實體類屬性需要依賴特別多的其他類時,bean的自動裝配可以幫我們減少xml中許多的配置。

package com.huang.pojo;

public

class

people

public

void

setcat

(cat cat)

public dog getdog()

public

void

setdog

(dog dog)

public string getname()

public

void

setname

(string name)

}

1.不使用bean自動裝配中xml的配置:

"cat"

class

="com.huang.pojo.cat"

/>

"dog"

class

="com.huang.pojo.dog"

/>

"people"

class

="com.huang.pojo.people"

>

name

="name"

value

="姓名"

/>

name

="dog"

ref="dog"

/>

name

="cat"

ref="cat"

/>

bean

>

因為這個例子中我們實體類需要依賴的其他模擬較少,所以配置bean的property屬性是覺得也不是很繁瑣,但是一旦我們需要依賴的其他類多了起來,property屬性的配置也就會越來越多,很麻煩。

2.使用bean自動裝配(通過byname):

"cat"

class

="com.huang.pojo.cat"

/>

"dog"

class

="com.huang.pojo.dog"

/>

"people"

class

="com.huang.pojo.people"

autowire

="byname"

>

name

="name"

value

="姓名"

/>

bean

>

通過設定bean的屬性autowire="byname"後,自動裝配便會在容器的上下文中查詢和自己物件屬性名字相同的id的bean並配置。

3.使用bean自動裝配(通過bytype):

"cat"

class

="com.huang.pojo.cat"

/>

"dog"

class

="com.huang.pojo.dog"

/>

"people"

class

="com.huang.pojo.people"

autowire

="bytype"

>

name

="name"

value

="姓名"

/>

bean

>

通過設定bean的屬性autowire="bytype"後,自動裝配便會在容器的上下文中查詢和自己物件屬性型別相同的bean,但是容器上下文中只能有乙個該型別的bean。

1.使用註解實現自動裝配必須先在xml中匯入所需依賴:

<?xml version="1.0" encoding="utf-8"?>

xmlns

=""xmlns:xsi

=""xmlns:context

=""xsi:schemalocation

=" /spring-beans.xsd

">

2.在xml中設定開啟註解支援:

<

context:annotation-config

/>

"dog"

class

="com.huang.pojo.dog"

/>

"cat"

class

="com.huang.pojo.cat"

/>

"people"

class

="com.huang.pojo.people"

/>

4.使用註解:

@autowired

private cat cat;

@autowired

@qualifier

(value =

"dog"

)private dog dog;

private string name;

注:@resource與@autowired註解都可註解在屬性的set方法上。

spring 自動裝配bean

在spring中,支援 5 自動裝配模式。public class customer public void setperson person person 要啟用 autowired,必須註冊 autowiredannotationbeanpostprocessor 可以使用在 set方法 構造方...

(Spring)自動裝配bean

自動裝配說明 spring的自動裝配需要從兩個角度來實現,或者說是兩個操作 元件掃瞄和自動裝配組合發揮巨大威力,使得顯示的配置降低到最少。public class cat public class dog public class people public void setcat cat cat ...

Spring自動裝配bean

configuration顯示這是乙個配置類,componentscan無其他配置則預設在該類所在包內開啟元件掃瞄,若有多個包則寫成 componentscan basepackages 若有多個類,則 componentscan basepackagesclasses package sounds...