Spring - Injecting Inner Beans

如您所知,Java内部类是在其他类的范围内定义的,类似地,内部bean 是在另一个bean的范围内定义的bean.因此,< bean/> < property/>内的元素或< constructor-arg/>元素称为内部bean,如下所示.

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

<beans xmlns = "https://img01.yuandaxia.cn/Content/img/tutorials/spring/"
   xmlns:xsi = "https://img01.yuandaxia.cn/Content/img/tutorials/spring/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>

示例

让我们使用Eclipse IDE并按照以下步骤创建Spring应用程序 :

Steps描述
1创建一个名为 SpringExample 的项目,并在创建的项目中的 src 文件夹下创建一个包 com.it1352.
2使用添加外部JAR添加所需的Spring库选项,如 Spring Hello World Example 章节中所述.
3 com.IT下创建Java类 TextEditor SpellChecker MainApp 包.
4 src 文件夹下创建Beans配置文件 Beans.xml .
5最后一步是创建所有Java文件和Bean配置文件的内容并运行应用程序如下所述.

以下是 TextEditor.java 文件的内容 : 号;

package com.it1352; 
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.it1352; 
public class SpellChecker {
   public SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }
   public void checkSpelling(){
      System.out.println("Inside checkSpelling." );
   }
}

以下是 MainApp.java 文件的内容 :

package com.it1352; 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
      TextEditor te = (TextEditor) context.getBean("textEditor");
      te.spellCheck();
   }
}

以下是配置文件 Beans.xml ,其中包含setter的配置 - 基于注射,但使用内豆 :

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

<beans xmlns = "https://img01.yuandaxia.cn/Content/img/tutorials/spring/"
   xmlns:xsi = "https://img01.yuandaxia.cn/Content/img/tutorials/spring/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.IT屋.TextEditor">
      <property name = "spellChecker">
         <bean id = "spellChecker" class = "com.IT屋.SpellChecker"/>
      </property>
   </bean>

</beans>

完成源和bean配置文件的创建后,让我们运行应用程序.如果您的应用程序一切正常,它将打印以下消息 :

Inside SpellChecker constructor.
Inside setSpellChecker.
Inside checkSpelling.