Skip to main content

Command Palette

Search for a command to run...

Spring boot proxyBeanMethods 作用

Updated
•1 min read•View as Markdown
Spring boot proxyBeanMethods 作用
J

meow meow meow meowwwww....

Ref

Overview

在 Spring boot 的 @Configuration 配置中, 常常看到 proxyBeanMethods = false 但並不是很理解. Spring boot 的文件內並沒有特別說明, 從原始碼註解與字面上大概知道會是把 proxy 的功能關閉. 於是 Google 相關資訊, 大致上是用於管理 Spring boot Configuration 內的 Bean 依賴關係.

Example

下面範例, 有個 Student 與 Teacher Beans, 而 Teacher 又依賴 Student. 故應 Spring boot 啟動時, 應該先注入 Student 再注入 Teacher 才不會發生問題.

@Configuration(proxyBeanMethods = false)
public class MyConfiguration {

  @Bean
  public Student student() {
    System.out.println("init student bean");
    return new Student();
  }

  @Bean
  public Teacher teacher() {
    System.out.println("init teacher bean");
    return new Teacher(student());
  }
}

但 spring boot 實際運行時會是

init student bean
init teacher bean
init student bean

Student Bean 被初始了兩次, 這可能是個大問題, 如果這個 Student 是資料庫相關配置, 可能會對 DB 連線兩次, 依據配置的複雜度 (可能又被使用在 Flyway Configuration 內, 會對 DB 做更多次連線). 這會導致 Spring boot 啟動緩慢, 且依據情境可能會產生一些 Spring boot context 相關錯誤.

上面的寫法在 IntelliJ (IntelliJ IDEA 2024.1.4 (Ultimate Edition)) 裡面會提示,

Method annotated with @Bean is called directly in a @Configuration where proxyBeanMethods set to false. Set proxyBeanMethods to true or use dependency injection.

IntelliJ 與 spring boot 整合的真的非常方便.

指示你應該採用 proxyBeanMethods = true 由 Spring boot 幫你處理.

或是改為注入的方式.

@Bean
public Teacher teacher(Student student) {
  System.out.println("init teacher");
  return new Teacher(student);
}

More from this blog

Java 轉換 COBOL COMP-3 資料

老舊的金融系統編碼問題 客戶的系統是早期的 IBM-Z (COBOL), 用的是 EBCDIC 的編碼, 而台灣的環境會搭配 BIG5(cp-950) 的編碼. EBCDIC 是 IBM 系統專用的編碼, 跟 ASCII 差異如下. 為了讓資了可以被處理, 需要進行資料清洗與解碼, 礙於客戶的資安規範與其他因素限制下, 合作過程必須處理 EBCDIC + Binary 的格式文件, 來做資料轉移. 資料格式 文字類型的 BIG5 編碼處理 中文的欄位資料是採用 Big5 (cp950), 撇開...

Jul 18, 20255 min read
Java 轉換 COBOL COMP-3 資料

DirtyPaw

21 posts