目录

Spring - Injecting Inner Beans

如您所知,Java内部类是在其他类的范围内定义的,类似地, inner beans是在另一个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>

例子 (Example)

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

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

这是TextEditor.java文件的内容 -

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

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

package com.iowiki;
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的注入配置,但使用inner beans -

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

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

Inside SpellChecker constructor.
Inside setSpellChecker.
Inside checkSpelling.
↑回到顶部↑
WIKI教程 @2018