第十二章 Spring内部Bean注入(Spring Framework3.1教程)

内部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.







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值