正如你所知道的 java 内部类是在其他类的范围内被定义的,同理,inner beans 是在其他 bean 的范围内定义的 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>
我们在适当的位置使用 eclipse ide,然后按照下面的步骤来创建一个 spring 应用程序:
步骤 | 描述 |
---|---|
1 | 创建一个名称为 springexample 的项目,并且在创建项目的 src 文件夹中创建一个包 com.tutorialspoint 。 |
2 | 使用 add external jars 选项,添加所需的 spring 库,解释见 spring hello world example 章节。 option as explained in the chapter. |
3 | 在 com.tutorialspoint 包中创建java类texteditor、spellchecker 和 mainapp。 |
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();
}
}
下面是使用内部 bean 为基于 setter 注入进行配置的配置文件 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>
一旦你创建源代码和 bean 配置文件完成后,我们就可以运行该应用程序。如果你的应用程序一切都正常,将输出以下信息:
inside spellchecker constructor.
inside setspellchecker.
inside checkspelling.