没有Spring之前,代码原来是这样写的!

        最近在看一位前辈的《Spring 开发指南》,才明白原来没有Spring之前,代码是这样写的。这对于我这个一开始学习Java EE编程就使用Spring的菜鸟级程序员来说,是很难理解Spring所带来的巨大便利的。以下是从这本电子书上几乎原封不动搬写下来的代码,作为自己学习Spring 原理的积累。

      首先,该项目是由用Myeclipse工具编写的,看一下整个Java 项目的结构图:

Action接口:

/**
 * Action接口.
 */
public interface Action {
	String execute(String name);
}

UpperAction类:

/**
 * UpperAction用来显示单词的大写形式.
 */
public class UpperAction implements Action{
	private String message;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
	
	public String execute(String name){
		return (this.getMessage() + name).toUpperCase();
	}
}
LowerAction类:

/**
 * LowerAction用来显示单词测小写形式.
 */
public class LowerAction implements Action {
	private String message;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
	@Override
	public String execute(String name) {
		return (this.getMessage() + name).toLowerCase();
	}
}

ActionFactory类:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;
import org.apache.commons.beanutils.BeanUtils;
/**
 * ActionFactory Action生成类.
 */
public class ActionFactory {
	public static Action getAction(String actionName){
		Properties pro = new Properties();
		try {
			pro.load(new FileInputStream(new File("config.properties")));
			String actionImplName = pro.getProperty(actionName);
			String actionMsg = pro.getProperty(actionName + "_msg");
			Object obj = Class.forName(actionImplName).newInstance();
			BeanUtils.setProperty(obj, "message", actionMsg);
			return (Action)obj;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		}catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return null;
	}
}

TestActionFactory类:

/**
 * ActionFactory测试类.
 */
public class TestActionFactory {
	public static void main(String[] args) {
		Action action = ActionFactory.getAction("TheAction");
		System.out.println(action.execute("\tno!"));
	}
}

config.properties文件:

TheAction=UpperAction
TheAction_msg=Red Hat

注:项目中要用的的commons-beanutils.jar 和 commons-logging.jar可以在 http://www.findjar.com/index.x站点搜到

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值