您的位置:首页 > 编程语言 > Java开发

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

2011-11-19 13:45 309 查看
最近在看一位前辈的《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站点搜到
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐