内部bean定义在另一个bean的内部,如你所知的Java内部类的定义一样在其他类的内部。因此一个<bean>元素定义在<property>或<constrtucor-arg/>元素内部被称作内部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>
示例
让我们按如下的步骤在Eclipse IDE中创建一个Spring应用:
步骤 | 描述 |
1 | 创建一个SpringExample的项目并在src目录下创建com.tutorialspoint包。 |
2 | 在Add External JARs选项卡中添加Spring库如在Spring Hello World章节中所讲。 |
3 | 在com.tutorialspoint包下创建TextEditor、SpellChecker和MainApp类。 |
4 | 在src目录下创建bean的配置文件Beans.xml |
5 | 最后一步在Java类中和Bean配置文件中添加内容,并运行应用。 |
如下是TextEditor的源代码:
package com.tutorialspoint;
public class TextEditor {
private SpellChecker spellChecker;
public void setSpellChecker(SpellChecker spellChecker) {
System.out.println("Inside setSpellChecker.");
this.spellChecker = spellChecker;
}
public SpellChecker getSpellChecker() {
return spellChecker;
}
public void spellCheck() {
spellChecker.checkSpelling();
}
}
如下是另一个依赖类SpellCheck的源代码:
package com.tutorialspoint;
public class SpellChecker {
public SpellChecker() {
System.out.println("Inside SpellChecker constructor.");
}
public void checkSpelling() {
System.out.println("Inside checkSpelling.");
}
}
如下是MainApp的源代码:
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();
}
}
如下是基于setter方法使用内部bean的配置文件Beans.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 using inner bean -->
<bean id="textEditor" class="com.tutorialspoint.TextEditor">
<property name="spellChecker">
<bean id="spellChecker" class="com.tutorialspoint.SpellChecker" />
</property>
</bean>
</beans>
一旦你完成了上面源代码和配置文件,运行应用,如果一切正常,会打印如下消息:
Inside SpellChecker constructor.
Inside setSpellChecker.
Inside checkSpelling.