Spring DI - 內部 Bean Setter 注入



正如您所知,Java 內部類是在其他類的範圍內定義的,類似地,**內部 Bean** 是在另一個 Bean 的範圍內定義的 Bean。因此,在<property/>或<constructor-arg/>元素內部的<bean/>元素稱為內部 Bean,如下所示。

<?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">
   <bean id = "outerBean" class = "...">
      <property name = "target">
         <bean id = "innerBean" class = "..."/>
      </property>
   </bean>
</beans>

示例

以下示例顯示了一個TextEditor類,它只能使用純基於 Setter 的注入進行依賴注入。

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

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

  • SpellChecker.java - 依賴類。

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

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

package com.tutorialspoint;

public class TextEditor {
   private SpellChecker spellChecker;
   
   // a setter method to inject the dependency.
   public void setSpellChecker(SpellChecker spellChecker) {
      System.out.println("Inside setSpellChecker." );
      this.spellChecker = spellChecker;
   }
   // a getter method to return spellChecker
   public SpellChecker getSpellChecker() {
      return 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,它具有基於 Setter 的注入的配置,但使用**內部 Bean** -

<?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 using inner bean -->
   <bean id = "textEditor" class = "com.tutorialspoint.TextEditor">
      <property name = "spellChecker">
         <bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker"/>
      </property>
   </bean>
</beans>

輸出

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

Inside SpellChecker constructor.
Inside setSpellChecker.
Inside checkSpelling.
廣告

© . All rights reserved.