快速上手spring(1 - 6)

来源:百度文库 编辑:神马文学网 时间:2024/04/29 15:14:41
1.收集的一些资料
“好的开始是成功的一半”,但凡一种新的技术,开始阶段一般是很苦恼的。为了不让更多的人走同样的弯路,我这里就把学习Spring的经验与大家分享, 一起快乐一下。
Spring是什么?反正这里我不会谈论春天的。我要说的是Spring Framework ,它又是用来做什么的呢?一会半会我也说不清楚。还好现在是互联网的时代,google一下,会发现不少有用的东西。
先来到Spring的大本营:http://www.springframework.org/  可以看看About Spring,最重要的是下载一个
Spring版本。
Spring的下载包有两种,一种是带有“with-dependencies”名称的,这种包含了Spring常用到的第三方包,比如Hibernate、aopalliance、jakarta-commons等。这里就使用了这种包,可以省却查找第三方包的麻烦。
当前版本1.2.1 :spring-framework-1.2.1-with-dependencies.zip
解压这个包,可以在 docs\reference目录下找到Spring 的参考手册,有html和pdf两种格式。如果你的英文不太好,可以看看Spring中文论坛翻译的1.1版本的中文版(pdf格式)。这个参考手册就是入门的不二法宝。
●     新手刚学Spring时,可能对一些概念似懂非懂,比如IoC(这里可不是国际奥委会)、DI等。这里向你推荐几篇好文章,有助于理解Spring。
· Rod Johnson:Introduction to Spring Framework (Spring 1.2版本)
Java视线论坛上翻译:Introducing to Spring Framework(中文修订版 旧版本)
· Robert C Martin, Bob: The Dependency Inversion Principle
· Martin Fowler:Inversion of Control Containers and the Dependency Injection pattern
透明对此文的翻译:IoC 容器和Dependency Injection 模式
· 冰云: 介绍 IOC
· 夏昕:Spring开发指南
· 良葛格:Spring入门(非常适合新手入门)
· javaboutique网站上有篇教程(入门):The Spring Framework
●   如果要系统的学习Spring,还是需要Book的。
·  Rod Johnson:Expert One-on-One J2EE Design and Development(10/2002)
看看作者是谁,就知道这本书的质量如何了。毫无疑问,这本书吹响了向Spring进军的号角。前半部分主要阐述了J2EE开发的方方面面的经验和设计,后半部分通过对J2EE的改善设计而引申出了SpringFramework。这本书的中译本也出来了,不过翻译的一般。
·  Rod Johnson, Juergen Hoeller:  Expert One-on-One J2EE Development without EJB(7/2004)
看看书名就会吓一跳,不过Rod Johnson完全有资格说出来。前半本介绍EJB的不足,后半本讲Spring的原理。这本书的中译本也出来了。
·  Bruce A. Tate, Justin Gehtland:Better, Faster, Lighter Java(5/2004)
这本书主要阐述了如何利用Java进行轻量级开发,有关Spring的内容比较少,只有一章,不过此书获得了Jolt 大奖,质量肯定没的说了。
·   Craig Walls, Ryan Breidenbach: Spring in Action(1/2005)
Manning出版的“in action”系列图书,质量一直非常好。此书系统介绍了Spring的方方面面,解析相当清晰。
·  Matt Raible:Spring Live
这本是source beat的电子书(只出电子版)。如果要深入这本书,需要有相当的基础。这本书非常适合有实践项目经验的人。采用TDD的方式使用Spring,而且提供Spring整合其他framework的各种作法 (相当多)。同时作者也维护着一个开源的项目appfuse。
·  Rob Harrop,Jan Machacek:Pro Spring(1/2005)
我目前只看过了样章,还很不错,很系统,也很细致,尤其书中提供的源代码很适合新手练习。
·  Rod Johnson等5人:Professional Java Development with the Spring Framework
预计2005年7月出版,作者阵容挺庞大的,几乎都是Spring开发团队的,值得期待。
·  罗时飞 精通Spring
这好像是目前为止系统介绍Spring的唯一简体中文书籍。
以上书籍都在网上提供了书中的源代码下载和部分样章,如果拿不到书,看看源代码也是很不错。
●  说完书籍,再介绍一些好的论坛。
·SpringFramework官方论坛
·SpringFramework中文论坛
·Matrix网站的Spring论坛
·Java视线论坛上的SpringFramework
最后给大家推荐一个不错的资源收集站点 http://www.java201.com/
在其右上方的搜索栏中填入“spring”,可以获得不少整理好的有关spring的资料。
好了,先写到这里了,以后会陆续添加一些好的资料和站点。
2.HelloWorld(1)
这篇文章主要谈谈Spring的入门开发,例子很简单,就是输出一条语句。有关各种软件的配置这里就不在多说了,如有不明白的,可以参考我以前的文章。
在开始看这篇文章之前,最好弄清楚IoC、DI等概念,参考《快速上手Spring--1.收集的一些资料》。
1. 所需软件
· JDK 5.0
·eclipse-SDK-3.1RC3-win32.zip
·xmlbuddy_2.0.62.zip
·spring-framework-1.2.1-with-dependencies.zip
如果安装后在Eclipse中看不到XmlBuddy,那么在eclipse命令后加上“-clean”参数。
2. 配置
●  配置Eclipse:
· Window->Perferences->Java->Compiler:将"Compiler compliance level"设为“5.0”
· Window->Perferences->Java->Build Path:勾选“Folders”
●  建立库文件夹
具体做法参考《Eclipse快速上手Hibernate--1. 入门实例》一文中的“建立库文件夹”的相关部分。
这里先将spring-framework-1.2.1-with-dependencies.zip解压,将其中的spring.jar(dist目录中)、commons-logging.jar(lib\jakarta-commons目录)、log4j-1.2.9.jar(lib\log4j目录)这三个文件复制到的”D:\java\Spring\lib" 目录中,然后在Eclipse中建立一个“Spring”库,将那三个文件添加进“Spring”库中。

1. 创建项目
· 新建一个Java Project:SpringHello,注意要导入用户库Spring。
· 这是完成后整个项目的结构(预览一下):

· 项目源码下载(不包含库文件):http://free.ys168.com/?javamxj  Spring目录下面。
2. 简单的HelloWorld
·下面开始创建一个新类:HelloWorld ;包名:javamxj.spring.beginning1,代码如下:
HelloWorld.java
package javamxj.spring.beginning1;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
OK!非常简单,我就是要它打印出一条语句“Hello World!”。
现在我不想输出“Hello World!”,我想随心所欲的输出任何语句,很简单啊!将“Hello World!”替换成所希望输出的语句即可。不过这样有一个缺点,每次修改好了,都需要重新编译一下程序。像这样的小程序固然无所谓,可是如果是一个大项目,这样做就有些讨厌了。
还好,只要稍微修改一下程序,通过参数输入即可。
· 继续在这个包下建立一个新类:HelloWorldWithCommandLine,同样非常简单:
HelloWorldWithCommandLine.java
package javamxj.spring.beginning1;
public class HelloWorldWithCommandLine {
public static void main(String[] args) {
if (args.length > 0) {
System.out.println(args[0]);
} else {
System.out.println("Hello World!");
}
}
}
· 选中HelloWorldWithCommandLine,右击->Run As->Run...,在弹出窗口切换到“Arguments”栏,在“program arguments”中填入“Hello,javamxj!”,如下图:

这样,就输出了我希望的语句。
第一部分到此,请继续看第二部分。
2.HelloWorld(2)
这是第二部分。
3. 采用“工厂模式”
· 新建一个包,包名:javamxj.spring.beginning2,在这个包下,新建一个“Hello”接口,这个接口含有一个方法。
Hello.java
package javamxj.spring.beginning2;
public interface Hello {
void sayHello();
}
· 分别新建两个类,实现这个接口。 HelloWorld.java
package javamxj.spring.beginning2;
public class HelloWorld implements Hello {
public void sayHello() {
System.out.println("Hello World!");
}
}
HelloJavamxj.java
package javamxj.spring.beginning2;
public class HelloJavamxj implements Hello {
public void sayHello() {
System.out.println("Hello, javamxj!");
}
}
· 建立一个工厂类,调用上面两个实现接口的子类。
HelloFactory.java
package javamxj.spring.beginning2;
public class HelloFactory {
public Hello getHello(String hello) {
if (hello.equals("world"))
return new HelloWorld();
else if (hello.equals("javamxj"))
return new HelloJavamxj();
else
throw new IllegalArgumentException("输入参数错误!");
}
}
· 最后,利用工厂类,测试一下。
Test.java
package javamxj.spring.beginning2;
public class Test {
public static void main(String[] args) {
Hello hello = null;
HelloFactory factory = new HelloFactory();
hello = factory.getHello("world");
hello.sayHello();
hello = factory.getHello("javamxj");
hello.sayHello();
}
}
运行Test,控制台输出如下语句:
Hello World!
Hello, javamxj!
4. Setter Injection
讲了这么多,似乎一点都不关Spring的事,别急,下面就看看用Spring是如何实现的。
· 新建一个包,包名:javamxj.spring.beginning3
· 在这个包下,新建一个HelloBean的类,这个类有一个属性:helloWorld属性,这个属性只是一个字符串。可以通过setHelloWorld方法设置这个属性,getHelloWorld方法得到这个属性。
HelloBean.java
package javamxj.spring.beginning3;
public class HelloBean {
private String helloWorld = "Hello!World!";
public void setHelloWorld(String helloWorld) {
this.helloWorld = helloWorld;
}
public String getHelloWorld() {
return helloWorld;
}
}
· 同样,在这个包下,建立一个XML文件,它是Spring配置文件。
bean.xml
xml version="1.0" encoding="GBK"?>
DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">



Hello! Javamxj!value>
property>
bean>
beans>
Spring配置文件必须遵循spring-beans.dtd定义的内容模型。
这个XML文件在Spring容器中声明了一个HelloBean的实例,并且将它的helloWorld属性设置为“Hello! Javamxj!”。
分析这个XML文件,位于根部的是元素,它是任何Spring配置文件的根元素。元素用于告诉Spring容器一个类以及它是如何配置的。这里,id属性用于为Bean helloBean命名,而class属性指定了这个Bean的全限定类名。
在元素内,元素用于设置一个属性,在本例中它是helloWorld属性。通过使用,我们告诉Spring容器当设置这个属性时调用setHelloWorld方法。greeting属性的值定义在元素内。在这里我设置为“Hello! Javamxj!”。
bean.xml必须在您的CLASSPATH可以存取到的目录中。
· 新建Main.java,测试一下。
Main.java
package javamxj.spring.beginning3;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Main {
public static void main(String[] args) {
// 直接调用HelloBean
HelloBean helloBean = new HelloBean();
System.out.println(helloBean.getHelloWorld());
// 利用Spring调用HelloBean
Resource res = new ClassPathResource("javamxj/spring/beginning3/bean.xml");
BeanFactory factory = new XmlBeanFactory(res);
helloBean = (HelloBean) factory.getBean("helloBean");
System.out.println(helloBean.getHelloWorld());
}
}
这里使用的BeanFactory类就是Spring容器。在将hello.xml文件装入容器后,main方法调用BeanFactory的getBean方法检索出了helloBean服务的一个引用。通过这个引用,它调用了getHelloWorld方法。当我们运行这个Hello应用时,它会打印出“Hello! Javamxj!”。
· 另外,为了更好的调试程序,了解运行机理,建立一个log4j.properties,放在src目录下。
src/log4j.properties
log4j.rootLogger=warn, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%c{1} - %m%n
5. Constructor Injection
· 新建一个包,包名:javamxj.spring.beginning3
· 新建一个HelloBean.java文件,可以与Setter Injection中的HelloBean比较一下,注意是通过Constructor设置helloWorld属性值的。
HelloBean.java
package javamxj.spring.beginning4;
public class HelloBean {
private String helloWorld;
public HelloBean(String helloWorld) {
this.helloWorld = helloWorld;
}
public void sayHello() {
System.out.println(helloWorld);
}
}
· 同样,在这个包下,也需要一个Spring配置文件。
bean.xml
xml version="1.0" encoding="GBK"?>
DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">



Hello! Javamxj!value>
constructor-arg>
bean>
beans>
这里通过来表示将使用 constructor injection。如果constructor的参数不只一个,那么需要利用index属性指定参数的位置索引,即,索引值从0开始。
· 测试一下。
Main.java
package javamxj.spring.beginning4;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Main {
public static void main(String[] args) {
Resource res = new ClassPathResource("javamxj/spring/beginning4/bean.xml");
BeanFactory factory = new XmlBeanFactory(res);
HelloBean helloBean = (HelloBean) factory.getBean("helloBean");
helloBean.sayHello();
}
}
这样,通过BeanFactory的getBean方法,以及xml配置文件,避免了在Main类中直接实例化HelloBean,消除了应用程序(Main)与服务(HelloBean)之间的耦合,实现了IOC(控制反转)或者说实现了依赖的注射(Dependency Injection)。
Setter Injection和Constructor Injection都有自己的长处和不足。至于,是选择Setter Injection,还是选择Constructor Injection?在《Spring in Action》、《Inversion of Control Containers and the Dependency Injection pattern》和《Spring开发指南》都有比较详细的论述,这里就不多说了。
3. 加载Bean的配置文件
1. 创建项目
· 新建一个Java Project:SpringBeanFile,注意要导入用户库Spring。
· 这是完成后整个项目的结构(预览一下):

· 项目源码下载(不包含库文件):http://free.ys168.com/?javamxj  Spring目录下面。
2. 编写类文件
· 下面开始创建一个新类:BeanFile ;包名:javamxj.spring.beanfile
BeanFile.java
package javamxj.spring.beanfile;
public class BeanFile {
private String beanFile = "多种方式加载Bean的配置文件";
public void setBeanFile(String beanFile) {
this.beanFile = beanFile;
}
public String getBeanFile() {
return beanFile;
}
}
· 新建Test.java,测试一下。
Test.java
package javamxj.spring.beanfile;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
// 直接调用HelloBean
BeanFile bf = new BeanFile();
System.out.println(bf.getBeanFile());
/**
* 利用XmlBeanFactory(Resource resource)
* 这里Resource必须是xml格式
* Resource包括:AbstractResource, ClassPathResource, FileSystemResource,
* InputStreamResource, ServletContextResource, UrlResource
*/
/*
* 利用 InputStreamResource(InputStream inputStream)
* 要将bean.xml放在项目根目录下
*/
InputStream is = null;
try {
is = new FileInputStream("bean1.xml");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Resource resource = new InputStreamResource(is);
sayHello(resource);
/*
* 利用 ClassPathResource(String path)
* 要将bean.xml放在源文件夹(src)目录下
*/
resource = new ClassPathResource("bean2.xml");
sayHello(resource);
/*
* 利用 FileSystemResource(String path)
* 要将bean.xml放在项目根目录下
*/
resource = new FileSystemResource("bean3.xml");
sayHello(resource);
/*
* 利用 Properties
* 要将bean.properties放在类路径--源文件夹(src)目录下
*/
BeanDefinitionRegistry reg = new DefaultListableBeanFactory();
PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(
reg);
reader.loadBeanDefinitions(new ClassPathResource("bean.properties"));
BeanFactory factory = (BeanFactory) reg;
bf = (BeanFile) factory.getBean("beanFile");
System.out.println("利用 " + bf.getBeanFile() + " 加载 Bean.properties");
/*
* 利用 ApplicationContext
* 要将bean.xml放在类路径--源文件夹(src)目录下
*/
ApplicationContext appContext = new ClassPathXmlApplicationContext(
"bean4.xml");
bf = (BeanFile) appContext.getBean("beanFile");
System.out.println("利用 " + bf.getBeanFile() + " 加载 Bean.xml");
}
public static void sayHello(Resource resource) {
BeanFactory factory = new XmlBeanFactory(resource);
BeanFile bf = (BeanFile) factory.getBean("beanFile");
System.out.println("利用 " + bf.getBeanFile() + " 加载 Bean.xml");
}
}
3. 配置文件
由上面的Test.java可知,这里一共需要四个XML文件和一个Properties文件,现在分别建立。
· bean1.xml放在项目根目录下:
bean1.xml
xml version="1.0" encoding="GBK"?>
DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">



InputStreamResource(InputStream inputStream)value>
property>
bean>
beans>
bean2.xml、bean3.xml、bean4.xml与bean1.xml相似,仅仅需要替换一下值即可。重要的注意文件的存放位置。这里只给出不同的代码;
· bean2.xml放在源文件夹(src)目录下:
bean2.xml(部分)

ClassPathResource(String path)value>
property>
· bean3.xml放在项目根目录下:
bean3.xml(部分)

FileSystemResource(String path)value>
property>
· bean4.xml放在源文件夹(src)目录下:
bean4.xml(部分)

ApplicationContextvalue>
property>
Spring也可以使用属性文件来定义配置文件,如下:
· bean.properties放在源文件夹(src)目录下:
bean.properties
beanFile.class=javamxj.spring.beanfile.BeanFile
beanFile.beanFile=properties
· 还需要将上文《快速上手Spring--2.HelloWorld(2)》中的log4j.properties复制到src目录下。
4. 运行程序
右击Test.java,运行程序,控制台输出如下:
多种方式加载Bean的配置文件
利用 InputStreamResource(InputStream inputStream) 加载 Bean.xml
利用 ClassPathResource(String path) 加载 Bean.xml
利用 FileSystemResource(String path) 加载 Bean.xml
利用 properties 加载 Bean.properties
利用 ApplicationContext 加载 Bean.xml
5. 小结
这篇文章主要谈论了如何加载Spring的配置文件,一般来说,就是BeanFactory和ApplicationContext。最常使用的、简单的BeanFactory实现是org.springframework.beans.factory.xml.XmlBeanFactory,其加载方式为:
BeanFactory factory = new XmlBeanFactory(Resource resource)
这里resource必须是xml格式。Resource包括: AbstractResource, ClassPathResource,  FileSystemResource, InputStreamResource, ServletContextResource,   UrlResource。这篇文章 谈了常用的三种:ClassPathResource,  FileSystemResource, InputStreamResource。
ApplicationContext包括了BeanFactory的所有功能,也要比BeanFactory强大的多(以后会详细介绍的)。这里只简单的使用了ClassPathXmlApplicationContext加载了Bean配置文件。你可以将log4j.properties中的“Warn”改为“Debug”, 对比一下和ClassPathResource的输出,
在Eclipse中,bean2.xml、bean4xml虽然都是放在源文件夹(src)目录下,但实际上,是由已经编译好的Test.class从类文件夹(这里是bin文件夹)中加载的。
4.安装和使用SpringIDE
这篇文章谈谈如何安装与使用SpringIDE。作为辅助Spring开发的工具,SpringIDE还是比较有用的。
● 软件配置:
· Eclipse 3.1
· SpringIDE
主页:http://springide.org/project/
当前版本:1.2.1  http://springide.org/updatesite/updatesite_1.2.1.zip
· GEF :只需要GEF Runtime就行了,3.1版本的下载地址。
● 安装:
· 解压安装GEF3.1,
· 在eclipe中打开 Help ->Software Updates ->Find and install,选择
Search for new features to install. 在打开的界面中,选择new archived site,选择下载的zip文件(如果没有下载这个zip文件,也可以选择New Remote Site,直接从网上更新),再选择一个安装的目录就可以了.

点击Next,在出现的对话框中勾选“updatesite_1.2.1.zip”,然后一直点击Next,直到安装完成。
· 如果有疑问,可以参考http://springide.org/project/wiki/SpringideInstall
● 使用:
这里以前面文章中的SpringHello项目实践一下如何使用SpringIDE。
· 右击SpringHello,在弹出菜单中选择“Add Spring Project Nature”,如下图:

如果成功,则这时该项目就会在右上角挂上了“S”.
· 右键项目名,查看其properties,选择“Spring Beans”,切换到“Config Files”,点击“Add”,将包javamxj.spring.beginning3下的bean.xml加入到其中。

· 这时可以看到bean.xml和HelloBean.java的右上角都挂上了“S”。

这是由于SpringIDE分析加载的bean.xml文件,找到了“helloBean”指向的类HelloBean.java。如果找不到这个文件,则会显示一个错误,指明这个类找不到;如果将“helloBean”指向了包javamxj.spring.beginning4下的bean.xml,虽然这个类存在,但由于属性不匹配,同样会显示出错误。这样就验证了XML的配置,可以提前知道配置中的错误。
· Spring Beans view
选中bean.xml,切换到“Navigate” ,如图:

· 显示图表,如图:

5.Bean的标志符(id与name)
又重新学习了Spring,想把自己的心得写下来,感觉有些无从下手。想来想去,还是根据Spring中文论坛翻译的《Spring Framework 开发参考手册》(1.1版本的中文版,pdf格式),来组织自己的思路。在这个阶段,我发布的关于Spring的文章,基本上都是入门级别的。相对而言,对于新手的帮助应该会更大。
虽然当前Spring的版本已经是1.2.2了,但同1.1版本的中文版相比,spring-reference还是相差不大的(尤其是前面几章的基础部分),所以采用的还是1.1版本的开发参考手册。
这个系列的文章,我准备根据开发参考手册的讲解,有针对性的增加大量的比较简单的实例,每个实例尽量只解释一个问题。下面就从3.2.4小节——《Bean的标志符(id与name)》讲起。
相关软件的配置可以参考《快速上手Spring--2.HelloWorld(1)》。
一般来说,在一个XmlBeanFactory中,定义一个bean时,采用的是的样式,如。
这里id的命名格式必须符合XML ID属性的命名规范,例如,不能以数字开头,“222”就不是合法的id值。为了解决这个问题,可以使用name属性指定一个和多个id(用逗号或者分号隔离)。
这里还是以HelloBean为例,这三个文件都放在包javamxj.spring.basic.aliases下。
· HelloBean
HelloBean.java
package javamxj.spring.basic.aliases;
public class HelloBean {
private String helloWorld = "Hello!World!";
public void setHelloWorld(String helloWorld) {
this.helloWorld = helloWorld;
}
public String getHelloWorld() {
return helloWorld;
}
}
· 配置文件
在这个Bean中,除了id属性,还含有name属性,其值为“2hello”、“javamxj@yahoo.com.cn”,因为以数字开头、含有特殊字符“@”,它们是不能用在id属性中的。
bean.xml
xml version="1.0" encoding="GBK"?>
DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

class="javamxj.spring.basic.aliases.HelloBean">

Hello! Javamxj!value>
property>
bean>
beans>
· 测试程序:
Main.java
package javamxj.spring.basic.aliases;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Main {
public static void main(String[] args) {
Resource res = new ClassPathResource( "javamxj/spring/basic/aliases/bean.xml");
BeanFactory factory = new XmlBeanFactory(res);
HelloBean helloBean  = (HelloBean) factory.getBean("helloBean");
HelloBean helloBean2 = (HelloBean) factory.getBean("2hello");
HelloBean helloBean3 = (HelloBean) factory.getBean("javamj@yahoo.com.cn");
System.out.println(helloBean.getHelloWorld());
// 验证是否指向同一个Bean
System.out.println((helloBean == helloBean2));
System.out.println((helloBean == helloBean3));
// 输出这个Bean的别名
String[] aliases = factory.getAliases("helloBean");
for (String str : aliases) {
System.out.println(str);
}
}
}
可以看出,使用中id属性和name属性几乎没有任何区别。
调用BeanFactory.getAliases(String)的方法时,传入的参数可以是任意一个Bean名字,输出的别名则是除去id之外的所有Bean名,如果没有指定id,则将其name属性中的第一个值指定为id。
当然,Bean的name属性不仅仅只是为了输入id属性所不允许的名字,它还有其它的用处,在后面的文章中会提及的。
6. Singleton的使用与否
上篇文章已经谈了《Spring Framework 开发参考手册》的3.2.4小节——《Bean的标志符(id与name)》,现在继续3.2.5小节——《Singleton的使用与否》。
文档已经把Singleton说的很清楚了,这里也不废话了。主要是了解在Spring中,默认的部署方式是Singleton,没有特别需要的话,一般使用Singleton。
相关软件的配置可以参考《快速上手Spring--2.HelloWorld(1)》。
这里还是以HelloBean为例,这三个文件都放在包javamxj.spring.basic.singleton下。
· HelloBean
这里多加了属性i,用它得到随机数。
HelloBean.java
package javamxj.spring.basic.singleton;
public class HelloBean {
private String helloWorld;
private int i = (int) (100 * Math.random());
public HelloBean(String helloWorld) {
this.helloWorld = helloWorld;
}
public void sayHello() {
System.out.println(helloWorld);
System.out.println("输出随机整数:  " + i);
}
}
· 配置文件
在这个Beans中,定义了两个bean,都指向HelloBean类,主要不同就是第二个bean指明了singleton="false",即不采用singleton部署方式。
bean.xml

"http://www.springframework.org/dtd/spring-beans.dtd">



Hello! 这是singletonBean!


singleton="false">

Hello! 这是prototypeBean!



· 测试程序:
分别取得singletonBean和prototypeBean各两个实例,然后输出随机数,最后比较同一个bean的两个实例的引用是否相同。
Main.java
package javamxj.spring.basic.singleton;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Main {
public static void main(String[] args) {
Resource res = new ClassPathResource("javamxj/spring/basic/singleton/bean.xml");
BeanFactory factory = new XmlBeanFactory(res);
HelloBean h1 = (HelloBean) factory.getBean("singletonBean");
h1.sayHello();
HelloBean h2 = (HelloBean) factory.getBean("singletonBean");
h2.sayHello();
System.out.println("h1==h2: " + (h1==h2));
System.out.println("");
HelloBean h3 = (HelloBean) factory.getBean("prototypeBean");
h3.sayHello();
HelloBean h4 = (HelloBean) factory.getBean("prototypeBean");
h4.sayHello();
System.out.println("h3==h4: " + (h3==h4));
}
}
·运行,控制台输出:
Hello! 这是singletonBean!
输出随机整数:  7
Hello! 这是singletonBean!
输出随机整数:  7
h1==h2: true
Hello! 这是prototypeBean!
输出随机整数:  95
Hello! 这是prototypeBean!
输出随机整数:  60
h3==h4: false
·这篇文章和上篇文章的源代码下载(不包含库文件):http://free.ys168.com/?javamxj  Spring目录下面的SpringBasic.zip。
_xyz