正如你所知道的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.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 | Create a project with a name SpringExample and create a package com.yiibai under the src folder in the created project. |
2 | Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter. |
3 | Create Java classes TextEditor, SpellChecker and MainApp under the com.yiibaipackage. |
4 | Create Beans configuration file Beans.xml under the src folder. |
5 | The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below. |
這裏是TextEditor.java文件的內容:
package com.yiibai;
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.yiibai;
public class SpellChecker {
public SpellChecker(){
System.out.println("Inside SpellChecker constructor." );
}
public void checkSpelling(){
System.out.println("Inside checkSpelling." );
}
}
以下是MainApp.java文件的內容:
package com.yiibai;
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.org/schema/beans/spring-beans-3.0.xsd">
<!-- Definition for textEditor bean using inner bean -->
<bean id="textEditor" class="com.yiibai.TextEditor">
<property name="spellChecker">
<bean id="spellChecker" class="com.yiibai.SpellChecker"/>
</property>
</bean>
</beans>
創建源代碼和bean配置文件來完成,讓我們運行應用程序。如果一切順利,這將打印以下信息:
Inside SpellChecker constructor.
Inside setSpellChecker.
Inside checkSpelling.
原文發佈時間爲:2018-10-21
本文作者:小白教程