一、实现目标

一种MVC【Model-View-Controller】一种设计模式,进行解耦。

/*
* 处理客户管理相关请求
*/
@Controller
public class CustomerController {
@Inject
private CustomService customService; @Action("get:/customer")
public View index(Param param) {
List<Customer> customerList = customService.getCustomerList("");
return new View("customer.jsp").addModel("customerlist", customerList);
} @Action("get:/customer_show")
public View show(Param param) {
long id = param.getLong("id");
Customer customer = customService.getCustomer(id);
return new View("customer_show.jsp").addModel("customer", customer);
} @Action("get:/customer_create")
public View create(Param param) {
return new View("customer_create.jsp");
} @Action("post:/customer_create")
public Data createSumbit(Param param) {
Map<String, Object> paramMap = param.getParamMap();
boolean result = customService.createCustomer(paramMap);
return new Data(result);
} @Action("get:/customer_edit")
public View edit(Param param) {
long id = param.getLong("id");
Customer customer = customService.getCustomer(id);
return new View("customer_edit.jsp").addModel("customer", customer);
} @Action("post:/customer_edit")
public Data editSumbit(Param param) {
long id = param.getLong("id");
Map<String, Object> paramMap = param.getParamMap();
boolean result = customService.updateCustomer(id, paramMap);
return new Data(result);
} @Action("post:/customer_delete")
public Data delete(Param param) {
long id = param.getLong("id");
boolean result = customService.deleteCustomer(id);
return new Data(result);
}
}

注:

  通过@Controller注解来定义Controller类;通过注解@Inject来定义成员属性;

  通过@Service注解来定义Service类,通过注解@Action来定义方法;

  返回View 对象标示jsp页面,Data标示JSon数据

二、代码开发

  https://github.com/bjlhx15/smart-framework.git 中的chapter3和smart-framework部分

三、知识点

3.1、类加载器

package com.lhx.smart.framework.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.io.File;
import java.io.FileFilter;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile; public class ClassUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(ClassUtil.class); /**
* 获取类加载器
*
* @return
*/
public static ClassLoader getClassLoader() {
return Thread.currentThread().getContextClassLoader();
} /**
* 加载类
*
* @param className
* @param isInitialized
* @return
*/
public static Class<?> loadClass(String className, boolean isInitialized) {
Class<?> cls;
try {
cls = Class.forName(className, isInitialized, getClassLoader());
} catch (ClassNotFoundException e) {
LOGGER.error("类加载失败", e);
throw new RuntimeException(e);
}
return cls;
} /**
* 获取制定报名下的所有类
*
* @param packageName
* @return
*/
public static Set<Class<?>> getClassSet(String packageName) {
Set<Class<?>> classSet = new HashSet<Class<?>>();
try {
Enumeration<URL> urls = getClassLoader().getResources(packageName.replace(".", "/"));
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
if (null != url) {
String protocol = url.getProtocol();
if (protocol.equals("file")) {
String packagePath = url.getPath().replaceAll("%20", " ");
addClass(classSet, packagePath, packageName);
} else if (protocol.equals("jar")) {
JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
if (jarURLConnection != null) {
JarFile jarFile = jarURLConnection.getJarFile();
if (jarFile != null) {
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement();
String jarEntryName = jarEntry.getName();
if (jarEntryName.endsWith(".class")) {
String className = jarEntryName.substring(0, jarEntryName.lastIndexOf(".")).replaceAll("/", ".");
doAddClass(classSet, className);
} }
}
}
}
}
}
} catch (Exception e) {
LOGGER.error("获取classSet 失败", e);
throw new RuntimeException(e);
}
return classSet;
} private static void addClass(Set<Class<?>> classSet, String packagePath, String packageName) {
File[] files = new File(packagePath).listFiles(new FileFilter() {
public boolean accept(File file) {
return (file.isFile() && file.getName().endsWith(".class")) || file.isDirectory();
}
});
for (File file : files) {
String fileName = file.getName();
if (file.isFile()) {
String className = fileName.substring(0, fileName.lastIndexOf("."));
if (StringUtils.isNotEmpty(packageName)) {
className = packageName + "." + className;
}
doAddClass(classSet, className);
} else {
String subPackagePath = fileName;
if (StringUtils.isNotEmpty(packagePath)) {
subPackagePath = packagePath + "/" + subPackagePath;
}
String subPackageName = fileName;
if (StringUtils.isNotEmpty(packageName)) {
subPackageName = packageName + "." + subPackageName;
}
addClass(classSet, subPackagePath, subPackageName);
}
}
} private static void doAddClass(Set<Class<?>> classSet, String className) {
Class<?> cls = loadClass(className, false);
classSet.add(cls);
}
}

3.2、反射工具类

package com.lhx.smart.framework.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.lang.reflect.Field;
import java.lang.reflect.Method; /**
* 反射工具类
*/
public final class ReflectionUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(ReflectionUtil.class); /**
* 创建实例
*
* @param cls
* @return
*/
public static Object newInstance(Class<?> cls) {
Object instance;
try {
instance = cls.newInstance();
} catch (Exception e) {
LOGGER.error("实例化失败", e);
throw new RuntimeException(e);
}
return instance;
} /**
* 调用方法
*
* @param obj
* @param method
* @param args
* @return
*/
public static Object invokeMethod(Object obj, Method method, Object... args) {
Object result;
try {
method.setAccessible(true);
result = method.invoke(obj, args);
} catch (Exception e) {
LOGGER.error("调用方法失败", e);
throw new RuntimeException(e);
}
return result;
} public static void setFiled(Object obj, Field field, Object value) {
try {
field.setAccessible(true);
field.set(obj, value);
} catch (Exception e) {
LOGGER.error("参数设置失败", e);
throw new RuntimeException(e);
}
}
}

003-搭建框架-实现IOC机制的更多相关文章

  1. Spring框架(3)---IOC装配Bean(注解方式)

    IOC装配Bean(注解方式) 上面一遍文章讲了通过xml来装配Bean,那么这篇来讲注解方式来讲装配Bean对象 注解方式需要在原先的基础上重新配置环境: (1)Component标签举例 1:导入 ...

  2. Sping框架的IOC特性 悲观锁、乐观锁 Spring的AOP特性

    Sping框架的IOC特性 IOC(Inversion of Control):控制反转 以下以课程与老师的安排来介绍控制反转. 一个合理的课程编排系统应该围绕培训的内容为核心,而不应该以具体的培训老 ...

  3. LCLFramework框架之IOC

    我们都知道,在采用面向对象方法设计的软件系统中,它的底层实现都是由N个对象组成的,所有的对象通过彼此的合作,最终实现系统的业务逻辑. 借助于"第三方"实现具有依赖关系的对象之间的解 ...

  4. [转]仿World Wind构造自己的C#版插件框架——WW插件机制精简改造

    很久没自己写东西啦,早该好好总结一下啦!一个大师说过“一个问题不应该被解决两次!”,除了一个好脑筋,再就是要坚持总结. 最近需要搞个系统的插件式框架,我参照World Wind的插件方式构建了个插件框 ...

  5. 3 weekend110的job提交的逻辑及YARN框架的技术机制 + MR程序的几种提交运行模式

    途径1: 途径2: 途径3: 成功! 由此,可以好好比较下,途径1和途径2 和途径3 的区别. 现在,来玩玩weekend110的joba提交的逻辑之源码跟踪 原来如此,weekend110的job提 ...

  6. 初学springMVC搭建框架过程及碰到的问题

    刚刚开始学spring框架,因为接了一个网站的项目,想用spring+springMVC+hibernate整合来实现它,现在写下搭建框架的过程及碰到的问题.希望给自己看到也能让大家看到不要踏坑. 一 ...

  7. Spring框架之IOC(控制反转)

    [TOC] 第一章Spring框架简介 IOC(控制反转)和AOP(面向方面编程)作为Spring框架的两个核心,很好地实现了解耦合.所以,简单来说,Spring是一个轻量级的控制反转(IoC)和面向 ...

  8. 从零开始搭建框架SSM+Redis+Mysql(二)之MAVEN项目搭建

    从零开始搭建框架SSM+Redis+Mysql(二)之MAVEN项目搭建 废话不说,直接撸步骤!!! 1.创建主项目:ncc-parent 选择maven创建项目,注意在创建项目中,packing选择 ...

  9. 从零开始搭建框架SSM+Redis+Mysql(一)之摘要

    从零开始搭建框架SSM+Redis+Mysql(一)之摘要 本文章为本人实际的操作后的回忆笔记,如果有步骤错漏,希望来信307793969@qq.com或者评论指出. 本文章只体现过程,仅体现操作流程 ...

随机推荐

  1. mysql 主库有数据通过锁库做主从

    master@localhost[(none)]> grant replication slave on *.* to 'repl'@'192.168.1.177' identified by ...

  2. Java多线程——不可变对象

    不可变对象条件 对象需要满足一下三个条件才是不可变对象: 1.对象创建以后其状态就不能修改 2.对象所有域都是final类型 3.对象是正确创建的(对象在创建期间,this引用没有溢出) 简而言之就是 ...

  3. 344. Reverse String【easy】

    344. Reverse String[easy] Write a function that takes a string as input and returns the string rever ...

  4. JVM物理结构和在内存中的组织结构

    对于JVM自身的物理结构,我们可以从下图鸟瞰一下: JVM内存组成结构 JVM栈由堆.栈.本地方法栈.方法区等部分组成,结构图如下所示: 1)堆 所有通过new创建的对象的内存都在堆中分配,其大小可以 ...

  5. Yarn源码分析之MRAppMaster上MapReduce作业处理总流程(二)

    本文继<Yarn源码分析之MRAppMaster上MapReduce作业处理总流程(一)>,接着讲述MapReduce作业在MRAppMaster上处理总流程,继上篇讲到作业初始化之后的作 ...

  6. 【转】Monkey测试4——Monkey命令行可用的全部选项

    Monkey命令行可用的全部选项 常规 --help 列出简单的用法. -v 命令行的每一个-v将增加反馈信息的级别. Level 0(缺省值)除启动提示.测试完成和最终结果之外,提供较少信息. Le ...

  7. iOS --发送手机验证码收不到手机验证码

    方法一:使用受信任设备上显示的验证码. 如果您的受信任设备是iOS 9 及以上系统时,则验证码将自动显示在受信任设备上.此时你信任的设备上会弹出你在某地登录ID位置的小地图,有一个选择允许与不允许登录 ...

  8. python导入模块报错:ImportError: No module named mysql.connector(安装 mysql)

    python的版本是 $ python --version Python 2.7.12 报错代码如下 import mysql.connector 报错信息是 ImportError: No modu ...

  9. HDU1087 Super Jumping! Jumping! Jumping! 最大连续递增子段

    Super Jumping! Jumping! Jumping! Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 ...

  10. pyhon多进程知识整理

    多进程概要: 在Unix/Linux下,可以使用fork()调用实现多进程. 要实现跨平台的多进程,可以使用multiprocessing模块. 进程间通信是通过Queue.Pipes等实现的. 要让 ...