Spring In Action

1.注入内部bean,也就是说这个bean不是所有类都可以引用的。

<bean id="student" class="com.xxc.test1.Student">
	<property name="game">
		<!-- 注入内部Bean,这个bean只提供给当前bean使用,其他bean无法引用,所以id也没必要写了 -->
		<bean class="com.xxc.test1.Wow"></bean>
	</property>
</bean>

2.使用Spring的命名空间p装配属性:

使用<property>元素为Bean的属性装配值和引用并不太复杂。尽管如此,Spring的命名空间p提供了另一种Bean属性的装配方式,该方式不需要配置如此多的尖括号。命名空间p的schema URI为xmlns:p="http://www.springframework.org/schema/p"。通过此声明,我们现在可以使用p:作为<bean>元素所有属性的前缀来装配Bean属性。

例子:

一个人类接口:

public interface Person {
	public void work();
}
一个游戏接口:

public interface Game {
	public void play();
}
一个学生实例:

public class Student implements Person {

	private Game game;

	public void work() {
		System.out.println("学生开始玩......");
		game.play();
	}

	public void setGame(Game game) {
		this.game = game;
	}

}

一个游戏实例:

public class Wow implements Game{

	public void play() {
		System.out.println("魔兽世界开玩......");
	}

}
applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
		xmlns:context="http://www.springframework.org/schema/context"
		xmlns:p="http://www.springframework.org/schema/p"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xmlns:aop="http://www.springframework.org/schema/aop" 
		xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
			http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-2.5.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
        
		<bean id="wow" class="com.xxc.test1.Wow"></bean>
		<bean id="student" class="com.xxc.test1.Student" p:game-ref="wow"></bean>
</beans>








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值