一、实现目标

一种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. 在训练CNN时,loss稳定在log(类别数)

    参见知乎问题! https://www.zhihu.com/question/275774218 很多框架都会有一个问题,当卷积 weight NaN 之后,卷积的 output 会变成 NaN.然后 ...

  2. rocketmq发送消息代码

    DefaultMQProducer defaultMQProducer = new DefaultMQProducer(); defaultMQProducer.setProducerGroup(Co ...

  3. 605. Can Place Flowers【easy】

    605. Can Place Flowers[easy] Suppose you have a long flowerbed in which some of the plots are plante ...

  4. linux清空文件夹命令问题

    1.linux删除命令是rm.2.命令为rm -rf /文件夹/文件名.3.例如:rm -f /a/b/d.log.删除在a文件夹中的b文件夹中的d.log这个文件.rm -rf /a/b.删除a文件 ...

  5. HDU 5355 Cake(2015多校第六场,搜索 + 剪枝)

    Cake Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others) Total Sub ...

  6. 非侵入式Ajax

    基本准备 首先,新建一个ASP.NET MVC 3的空项目. 然后新增一个Model,代码如下: using System; using System.Collections.Generic; usi ...

  7. Who's in the Middle - poj 2388 (快速排序寻找中位数)

    题意; 寻找中位数 利用快速排序来寻找中位数. #include <iostream> using namespace std; int N; ]; int Median(int left ...

  8. Servlet 国际化

    在我们开始之前,先来看看三个重要术语: 国际化(i18n):这意味着一个网站提供了不同版本的翻译成访问者的语言或国籍的内容. 本地化(l10n):这意味着向网站添加资源,以使其适应特定的地理或文化区域 ...

  9. Hibernate生成器类

    在Hibernate中,id元素的<generator>子元素用于生成持久化类的对象的唯一标识符. Hibernate框架中定义了许多生成器类. 所有的生成器类都实现了org.hibern ...

  10. MySQL左连接查询

    1.语法: select 字段列表 from table1 别名1 left join table2 别名2 on 连接条件 [where 子句]