Spring學習(一) 裝配bean(1)

2021-09-10 01:38:48 字數 2504 閱讀 3182

在便利性方面最強大的是spring的自動化配置,我感覺這個也確實是用起來最方便的

首先,spring是從兩個角度來實現自動化裝配:

元件掃瞄:spring會自動發現應用上下文中所建立的bean

自動裝配:spring自動滿足bean之間的依賴

下面來看spring是如何建立bean,如何掃瞄bean,又如何裝配的,我們以cd為例子

建立bean

我們先定義cd這個介面,cd中有乙個play功能

package soundsystem;

public inte***ce compactdisc

然後我們來實現這個介面,就弄乙個叫lemon的cd吧

package soundsystem;

import org.springframework.stereotype.component;

@component

public class lemon implements compactdisc

}

應該很容易發現乙個特別的東西,就是@component註解,這個註解表明這個類會作為元件類,並告知spring要我這個類建立bean,不過元件掃瞄預設是不啟用的,所以我們要顯示配置一下spring,從而讓它去找到那些帶有@component註解的類,並為其建立bean

那麼接下來就是啟用元件掃瞄去找到這個lemon類了(順帶一提,下面的cdplayer也是靠這個類去掃瞄的,因為都在乙個包中),這個過程也非常簡單,我們寫乙個配置類即可

package soundsystem;

import org.springframework.context.annotation.componentscan;

import org.springframework.context.annotation.configuration;

@configuration

@componentscan

public class cdplayerconfig

我們只要新增乙個@configuration註解和乙個@componentscan註解即可,@configuration註解表明這個類是乙個配置類,而@componentscan則是啟動元件掃瞄,如果沒有其他配置,@componentscan會預設掃瞄與配置類相同的包,如果你想掃瞄其他的包的話有下面三種方式

@componentscan("soundsystem")   //包名

@componentscan(basepackages = ) //包名

@componentscan(basepackageclasses = ) //類名

3.接下來我們把這張《lemon》cd放到(注入)cdplayer中去

package soundsystem;

import org.springframework.beans.factory.annotation.autowired;

import org.springframework.stereotype.component;

@component

public class cdplayer

public void play()

}

@autowired是自動裝配

4.最後我們來驗證一下自動裝配是否成功了,建立乙個cdplayertest類

package soundsystem;

import org.springframework.beans.factory.annotation.autowired;

import org.springframework.test.context.activeprofiles;

import org.springframework.test.context.contextconfiguration;

import org.springframework.test.context.junit4.springjunit4classrunner;

import static org.junit.assert.*;

import org.junit.test;

import org.junit.runner.runwith;

@runwith(springjunit4classrunner.class)

@contextconfiguration(classes=cdplayerconfig.class)

public class cdplayertest

}

我這裡是用的junit測試單元測試的@runwith就是告訴spring,這個用junit4來測試,@contextconfiguration則是告訴spring配置類在是哪個,最後執行的結果:

spring學習筆記(一) bean的裝配

id,class,scope,construtor arguments,properties,autowiring mode,lazy init 是否懶載入 abstract 是否是抽象的不需要例項化 init method,destroy method autowiring mode 自動裝配模式...

Spring 自動裝配bean學習筆記

當實體類屬性需要依賴特別多的其他類時,bean的自動裝配可以幫我們減少xml中許多的配置。package com.huang.pojo public class people public void setcat cat cat public dog getdog public void setdo...

spring 基本Bean裝配

在基於spring的應用中,應用元件在spring中是啟用的。容器可以建立元件,裝配和配置元件,以及管理它們的整個生 命週期。容器是spring 框架的核心,spring容器使用di管理所有組成應用系統的元件。spring容器提供多個spring 容器。spring容器提供了多種容器,並分為兩類。b...