003-搭建框架-实现IOC机制
一、实现目标
一种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机制的更多相关文章
- Spring框架(3)---IOC装配Bean(注解方式)
IOC装配Bean(注解方式) 上面一遍文章讲了通过xml来装配Bean,那么这篇来讲注解方式来讲装配Bean对象 注解方式需要在原先的基础上重新配置环境: (1)Component标签举例 1:导入 ...
- Sping框架的IOC特性 悲观锁、乐观锁 Spring的AOP特性
Sping框架的IOC特性 IOC(Inversion of Control):控制反转 以下以课程与老师的安排来介绍控制反转. 一个合理的课程编排系统应该围绕培训的内容为核心,而不应该以具体的培训老 ...
- LCLFramework框架之IOC
我们都知道,在采用面向对象方法设计的软件系统中,它的底层实现都是由N个对象组成的,所有的对象通过彼此的合作,最终实现系统的业务逻辑. 借助于"第三方"实现具有依赖关系的对象之间的解 ...
- [转]仿World Wind构造自己的C#版插件框架——WW插件机制精简改造
很久没自己写东西啦,早该好好总结一下啦!一个大师说过“一个问题不应该被解决两次!”,除了一个好脑筋,再就是要坚持总结. 最近需要搞个系统的插件式框架,我参照World Wind的插件方式构建了个插件框 ...
- 3 weekend110的job提交的逻辑及YARN框架的技术机制 + MR程序的几种提交运行模式
途径1: 途径2: 途径3: 成功! 由此,可以好好比较下,途径1和途径2 和途径3 的区别. 现在,来玩玩weekend110的joba提交的逻辑之源码跟踪 原来如此,weekend110的job提 ...
- 初学springMVC搭建框架过程及碰到的问题
刚刚开始学spring框架,因为接了一个网站的项目,想用spring+springMVC+hibernate整合来实现它,现在写下搭建框架的过程及碰到的问题.希望给自己看到也能让大家看到不要踏坑. 一 ...
- Spring框架之IOC(控制反转)
[TOC] 第一章Spring框架简介 IOC(控制反转)和AOP(面向方面编程)作为Spring框架的两个核心,很好地实现了解耦合.所以,简单来说,Spring是一个轻量级的控制反转(IoC)和面向 ...
- 从零开始搭建框架SSM+Redis+Mysql(二)之MAVEN项目搭建
从零开始搭建框架SSM+Redis+Mysql(二)之MAVEN项目搭建 废话不说,直接撸步骤!!! 1.创建主项目:ncc-parent 选择maven创建项目,注意在创建项目中,packing选择 ...
- 从零开始搭建框架SSM+Redis+Mysql(一)之摘要
从零开始搭建框架SSM+Redis+Mysql(一)之摘要 本文章为本人实际的操作后的回忆笔记,如果有步骤错漏,希望来信307793969@qq.com或者评论指出. 本文章只体现过程,仅体现操作流程 ...
随机推荐
- excel文件打开乱码解决
Excel在读取csv的时候是通过读取文件头上的bom来识别编码的,如果文件头无bom信息,则默认按照unicode编码读取.(这个bom是微软自己定义的一种文件头部协定,顾名思义存储在文件头部,存储 ...
- Atitit.自定义jdbc驱动 支持jsql
Atitit.自定义jdbc驱动 支持jsql 1. 为什么需要自定义驱动1 1.1. 透明分库分表1 1.2. 自定义数据库的接口.比如大数据文档文件类型的数据库,数据存储引擎2 2. 整个文章分 ...
- Java平台调用.net开发的WebService报错处理
1.报错:服务器未能识别 HTTP 头 SOAPAction 的值 : 解决办法:.net 开发的WebService文件中(.asmx)增加属性: [SoapDocumentService(Rout ...
- JsCal( JS Calendar)
http://www.dynarch.com/projects/calendar Doc: http://www.dynarch.com/jscal/ This is the documentatio ...
- JAVA热部署原理
1.热部署是什么? 对于Java应用程序来说,热部署就是在运行时更新Java类文件. 2.热部署有什么用? 可以不重启应用的情况下,更新应用.举个例子,就像电脑可以在不重启的情况下,更换U盘. OSG ...
- Creating Dialogbased Windows Application (4) / 创建基于对话框的Windows应用程序(四)Edit Control、Combo Box的应用、Unicode转ANSI、Open File Dialog、文件读取、可变参数、文本框自动滚动 / VC++, Windows
创建基于对话框的Windows应用程序(四)—— Edit Control.Combo Box的应用.Unicode转ANSI.Open File Dialog.文件读取.可变参数.自动滚动 之前的介 ...
- Redis提供商配置ASP.NET会话状态
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Co ...
- PILE读书笔记_基础知识
程序的构成 Linux下二进制可执行程序的格式一般为ELF格式. 我们可以用readelf命令来读取二进制的信息. ELF文件的主要内容就是由各个section及symbol表组成的. 下面来分别介绍 ...
- awk按列求和
awk 'BEGIN{total=0}{total+=$1}END{print total}'
- 学习抓包之如何用Charles实现“刷楼”
为了获取一些网络中的数据,我们需要掌握抓包技术. Charles是一个 HTTP 代理服务器, HTTP 监视器,反转代理服务器.它允许一个开发者查看所有连接互联网的 HTTP 通信.这些包括Requ ...