Spring注入内部bean
如你所知道的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.manongjc 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.manongjcpackage. |
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.manongjc;
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.manongjc;
public class SpellChecker {
public SpellChecker(){
System.out.println("Inside SpellChecker constructor." );
}
public void checkSpelling(){
System.out.println("Inside checkSpelling." );
}
}
以下是MainApp.java文件的内容:
package com.manongjc;
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.manongjc.TextEditor">
<property name="spellChecker">
<bean id="spellChecker" class="com.manongjc.SpellChecker"/>
</property>
</bean>
</beans>
创建源代码和bean配置文件来完成,让我们运行应用程序。如果一切顺利,这将打印以下信息:
Inside SpellChecker constructor.
Inside setSpellChecker.
Inside checkSpelling.