Spring DI - 基於建構函式的依賴注入



基於建構函式的依賴注入是在容器呼叫類的建構函式,並傳入多個引數(每個引數代表對其他類的依賴)時實現的。

示例

以下示例顯示了一個只能透過建構函式注入進行依賴注入的類TextEditor

讓我們更新在Spring DI - 建立專案章節中建立的專案。我們將新增以下檔案:

  • TextEditor.java - 一個包含SpellChecker作為依賴項的類。

  • SpellChecker.java - 一個依賴類。

  • MainApp.java - 執行和測試的主應用程式。

以下是TextEditor.java檔案的內容:

package com.tutorialspoint;

public class TextEditor {
   private SpellChecker spellChecker;
   
   public TextEditor(SpellChecker spellChecker) {
      System.out.println("Inside TextEditor constructor." );
      this.spellChecker = spellChecker;
   }
   public void spellCheck() {
      spellChecker.checkSpelling();
   }
}

以下是另一個依賴類檔案SpellChecker.java的內容:

package com.tutorialspoint;
public class SpellChecker {
   public SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }
   public void checkSpelling() {
      System.out.println("Inside checkSpelling." );
   }
}

以下是MainApp.java檔案的內容。

package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml");

      TextEditor te = (TextEditor) context.getBean("textEditor");
      te.spellCheck();
   }
}

以下是包含基於建構函式注入配置的配置檔案applicationcontext.xml

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

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <!-- Definition for textEditor bean -->
   <bean id = "textEditor" class = "com.tutorialspoint.TextEditor">
      <constructor-arg ref = "spellChecker"/>
   </bean>

   <!-- Definition for spellChecker bean -->
   <bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker"></bean>
</beans>

輸出

建立原始檔和Bean配置檔案後,讓我們執行應用程式。如果應用程式一切正常,它將列印以下訊息:

Inside SpellChecker constructor.
Inside TextEditor constructor.
Inside checkSpelling.
廣告
© . All rights reserved.