Spring In Action

来源:互联网 发布:java struct 简单案列 编辑:程序博客网 时间:2024/05/03 08:53

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.xsdhttp://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>