/**
作者:willpower
来源:rifoo technology(http://www.rifoo.com)
时间:2005-12-29
备注:转载请保留以上声明
**/
本篇主要介绍使用spring来进行依赖注入,以及对以前代码的改进。
如果你机器上没有安装spring,需要先到官方网站(http://www.springframework.org)上去下载,将spring的lib放到war\web-inf\lib下,让应用能够找到它们。
将现有应用程序转移到一个设计良好的pojo的基于spring的应用其实很简单,只需要以下几个步骤:
1 利用依赖注入的思想对现有代码进行重构。model对象看作bean,service看作aspect。一般我们只有bean,而没有使用到service。
2 去掉代码中实例化对象和设置依赖(即通过set方法设置)的那部分代码。
3 创建一个配置文件来描述bean和aspect。
4 通过spring来访问我们的代码。
下面我们就按照上面的步骤来改进我们的程序:
先看看管理我们bean和aspect的配置文件,目前这里没有用到aspect。
example 1-9. rentabike-context.xml
<?xml version="1.0" encoding="utf-8"?>
<beans>
<bean id="rentabike" class="arraylistrentabike">
<property name="storename"><value>"bruce's bikes"</value></property>
</bean>
<bean id="commandlineview" class="commandlineview">
<property name="rentabike"><ref bean="rentabike"/></property>
</bean>
</beans>
import org.springframework.context.support.classpathxmlapplicationcontext;
public class rentabikeassembler {
public static final void main(string[] args) {
//使用这一句来读取上面定义的配置文件
classpathxmlapplicationcontext ctx = new
classpathxmlapplicationcontext("rentabikeapp-context.xml");
//完成依赖注入
commandlineview clv =
(commandlineview)ctx.getbean("commandlineview");
clv.printallbikes( );
}
}
public class rentabikeassembler {
public static final void main(string[] args) {
commandlineview clv = new commandlineview( );//1
rentabike rentabike = new arraylistrentabike("bruce's bikes");//2
clv.setrentabike(rentabike);//3
clv.printallbikes( );
}
}Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器