一、实现目标

一种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. go实现定时功能两种方法

    1:timer 学习自:https://studygolang.com/articles/2479 timer1 := time.NewTimer(time.Second * 2) //此处在等待ch ...

  2. docker mongo backup 不用找啦,就在这里。

    rm -rf /tmp/mongodump && mkdir /tmp/mongodumpdocker run -it --rm --link lps-mongodb:mongo -v ...

  3. Atitit.通过null 参数 反射  动态反推方法调用

    Atitit.通过null 参数 反射  动态反推方法调用 此时,直接使用java  apache的ref工具都失效了.必须要自己实现了. 如果调用接口方法的话,就不能使用apache的ref工具,可 ...

  4. Qt5 CMake cross compile

    cmake_minimum_required(VERSION 2.8) if (${ARM}) set(CMAKE_SYSTEM_NAME Linux) set(CMAKE_SYSTEM_PROCES ...

  5. ASP.NET MVC 表单提交多层子级实体集合数据到控制器中

    于遇到了项目中实体类嵌套多层子级实体集合,并且子级实体集合的数据需要提交保存到数据库中的问题.针对此情况需要进行一些特殊的处理才可以将整个 实体类及子级实体集合数据提交表单到控制器中,解决的方法是根据 ...

  6. flex初始化方法

    initalize是初始化,creationcomplete是创建完成,applicationComplete是应用程序中所有的实例都创建完成后才执行,三者的执行顺序是intalize creatio ...

  7. RL for Robots

    1.Robot gains Social Intelligence through Multimodal Deep Reinforcement Learning 这篇文章使用DQN去训练一个机器人,使 ...

  8. 第一百七十一节,jQuery,高级事件,模拟操作,命名空间,事件委托,on、off 和 one

    jQuery,高级事件,模拟操作,命名空间,事件委托,on.off 和 one 学习要点: 1.模拟操作 2.命名空间 3.事件委托 4.on.off 和 one jQuery 不但封装了大量常用的事 ...

  9. freemark 页面静态化

    1. 页面静态化是什么? 页面静态化有非常多含义,在WEB开发中.静态网页一般理解为站点中大部分超级链接所引用的页面是单独的HTML静态页面文件(如.htm..html等页面文件,html语言本身是静 ...

  10. 【独立开发人员er Cocos2d-x实战 013】Cocos2dx 网络编程实战之星座运势

    学习cocos2d-x和cocos creator的圈子:cocos2d-x:436689827    cocos creator:124727696 本篇文章主要内容:jsoncpp的使用,Coco ...