如您所知,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.or...d">

<bean id = "outerBean" class = "...">

  <property name = "target">     <bean id = "innerBean" class = "..."/>  </property>

</bean>

</beans>
例子
让咱们应用 Eclipse IDE 并依照以下步骤创立一个 Spring 应用程序 -

脚步 形容
1 创立一个名为SpringExample的我的项目,并在创立的我的项目的src文件夹下创立一个包com.tutorialspoint。
2 应用增加内部 JAR选项增加所需的 Spring 库,如Spring Hello World 示例章节中所述。
3 创立Java类文本编辑,拼写检查和MainApp下com.tutorialspoint包。
4 在src文件夹下创立 Beans 配置文件Beans.xml。
5 最初一步是创立所有 Java 文件和 Bean 配置文件的内容并运行应用程序,如下所述。
这是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("Beans.xml");  TextEditor te = (TextEditor) context.getBean("textEditor");  te.spellCheck();

}
}
以下是配置文件Beans.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.or...d">

<!-- 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.