底層註解 Configuration詳解

2021-10-21 21:13:24 字數 3222 閱讀 5926

首先給出專案的目錄結構,其中需要注入的元件是user類和pet類。

="張三"

>

property

>

name

="userage"

value

="25"

>

property

>

bean

>

"pet01"

class

="com.hpf.boot.bean.pet"

>

name

="petype"

value

="湯姆貓"

>

property

>

bean

>

import com.hpf.boot.bean.pet;

import com.hpf.boot.bean.user;

import org.springframework.context.annotation.bean;

import org.springframework.context.annotation.configuration;

/** 1.配置類裡面使用@bean標註在方法上給容器註冊元件,預設是單例項的

* 2.配置類本身也是元件

* 3.boolean proxybeanmethods() default true;**bean的方法

* full模式(全模式):proxybeanmethods = true

* lite模式(輕量級模式):proxybeanmethods = false

* 這個設定主要是為了解決元件依賴問題

* */

@configuration

(proxybeanmethods =

true

)//告訴springboot這是乙個配置類==配置檔案

public

class

myconfig

@bean

("tom"

)//這裡可以設定自定義元件的名字

public pet pet01()

}

在主程式類裡面可是測試一下**:

import com.hpf.boot.bean.pet;

import com.hpf.boot.bean.user;

import com.hpf.boot.config.myconfig;

/* 主程式類

* 告訴編譯器這是乙個springboot應用*/

(scanbasepackages =

"com.hpf"

)public

class

*///3.從容器中獲取元件

pet tom01= run.

getbean

("tom"

, pet.

class);

pet tom02= run.

getbean

("tom"

, pet.

class);

//可以證明向容器中注入的元件是單例項的

system.out.

println

(tom01==tom02)

;//說明配置類本身也是乙個元件

myconfig bean = run.

getbean

(myconfig.

class);

system.out.

println

(bean)

;//如果@configuration(proxybeanmethods = true)**物件呼叫方法,springboot總會檢查這個元件是否在容器裡面

//也就是說springboot會保持元件單例項

user user01 = bean.

user01()

; user user02 = bean.

user01()

; system.out.

println

(user01==user02);}

}

接下來我們用**的形式測試一下元件依賴具體說的是什麼意思?

@configuration

(proxybeanmethods =

true

)//告訴springboot這是乙個配置類==配置檔案

public

class

myconfig

@bean

("tom"

)//這裡可以設定自定義元件的名字

public pet pet01()

}//以下是主程式的測試**

myconfig bean = run.

getbean

(myconfig.

class);

//獲取乙個寵物元件

pet tom01 = run.

getbean

("tom"

, pet.

class);

system.out.

println

(tom01)

;//獲取乙個使用者元件

user user01 = run.

getbean

("user01"

,user.

class);

system.out.

println

(user01.

getpet()

);

可以看到當proxybeanmethods = true時,使用者的寵物就是容器裡面的寵物。

可以看到當proxybeanmethods = false時,使用者的寵物並不是容器裡面的寵物。

配置類元件之間無依賴關係用lite模式加速容器啟動過程,減少判斷;

配置類元件之間有依賴關係,方法會被呼叫之前單例項元件,用full模式

SpringBoot底層註解

1.configuration 基本使用package com.marchsoft.boot.config import com.marchsoft.boot.bean.pet import com.marchsoft.boot.bean.user import org.springframewor...

Configuration等底層註解

一般會基本使用 知曉 full模式與lite模式 最佳實戰主要有如下兩點 配置 類元件之間無依賴關係用lite模式加速容器啟動過程,減少判斷 配置類元件之間有依賴關係,方法會被呼叫得到之前單例項元件,用full模式 1 配置類裡面使用 bean標註在方法上給容器註冊元件,預設也是單例項的 2 配置類...

註解底層是怎麼實現業務邏輯的

通過以下例子來解釋 首先寫乙個介面並實現這個介面 隨便建乙個介面,這裡就寫乙個userservice public inte ce userservice 然後實現userservice介面,並隨意寫一些方法用來測試 public class userserviceimpl implements u...