本文主要是介绍《架构探险从零开始写javaweb》总结,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
导读:
- IOC(实现加载指定路径的类,实现加载指定注解的类,放在Map<Class<?>, Object>中)
- AOP (先将目标类的所有的切面类找出来,链式的将切面代理类作为目标类的增强返回新的bean,替换原来的bean到map中。)
- DI(将类中需要注入bean的属性,反射注入进去)
- MVC (根据方法上的注解将请求路径、类、方法存入Map<Request, Handler>中,所有请求在DispatcherServlet的service方法解析)
1、控制反转
实现加载指定路径的类,实现加载指定注解的类,放在Map<Class<?>, Object>中
package org.smart4j.framework.util;import java.io.File;
import java.io.FileFilter;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;/*** 类操作工具类** @author huangyong* @since 1.0.0*/
public final class ClassUtil {private static final Logger LOGGER = LoggerFactory.getLogger(ClassUtil.class);/*** 获取类加载器*/public static ClassLoader getClassLoader() {return Thread.currentThread().getContextClassLoader();}/*** 加载类*/public static Class<?> loadClass(String className, boolean isInitialized) {Class<?> cls;try {cls = Class.forName(className, isInitialized, getClassLoader());} catch (ClassNotFoundException e) {LOGGER.error("load class failure", e);throw new RuntimeException(e);}return cls;}/*** 加载类(默认将初始化类)*/public static Class<?> loadClass(String className) {return loadClass(className, true);}/*** 获取指定包名下的所有类*/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 (url != null) {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> jarEntries = jarFile.entries();while (jarEntries.hasMoreElements()) {JarEntry jarEntry = jarEntries.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("get class set failure", 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 (StringUtil.isNotEmpty(packageName)) {className = packageName + "." + className;}doAddClass(classSet, className);} else {String subPackagePath = fileName;if (StringUtil.isNotEmpty(packagePath)) {subPackagePath = packagePath + "/" + subPackagePath;}String subPackageName = fileName;if (StringUtil.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);}
}
package org.smart4j.framework.helper;import java.lang.annotation.Annotation;
import java.util.HashSet;
import java.util.Set;
import org.smart4j.framework.annotation.Controller;
import org.smart4j.framework.annotation.Service;
import org.smart4j.framework.util.ClassUtil;/*** 类操作助手类** @author huangyong* @since 1.0.0*/
public final class ClassHelper {/*** 定义类集合(用于存放所加载的类)*/private static final Set<Class<?>> CLASS_SET;static {String basePackage = ConfigHelper.getAppBasePackage();CLASS_SET = ClassUtil.getClassSet(basePackage);}/*** 获取应用包名下的所有类*/public static Set<Class<?>> getClassSet() {return CLASS_SET;}/*** 获取应用包名下所有 Service 类*/public static Set<Class<?>> getServiceClassSet() {Set<Class<?>> classSet = new HashSet<Class<?>>();for (Class<?> cls : CLASS_SET) {if (cls.isAnnotationPresent(Service.class)) {classSet.add(cls);}}return classSet;}/*** 获取应用包名下所有 Controller 类*/public static Set<Class<?>> getControllerClassSet() {Set<Class<?>> classSet = new HashSet<Class<?>>();for (Class<?> cls : CLASS_SET) {if (cls.isAnnotationPresent(Controller.class)) {classSet.add(cls);}}return classSet;}/*** 获取应用包名下所有 Bean 类(包括:Service、Controller 等)*/public static Set<Class<?>> getBeanClassSet() {Set<Class<?>> beanClassSet = new HashSet<Class<?>>();beanClassSet.addAll(getServiceClassSet());beanClassSet.addAll(getControllerClassSet());return beanClassSet;}/*** 获取应用包名下某父类(或接口)的所有子类(或实现类)*/public static Set<Class<?>> getClassSetBySuper(Class<?> superClass) {Set<Class<?>> classSet = new HashSet<Class<?>>();for (Class<?> cls : CLASS_SET) {if (superClass.isAssignableFrom(cls) && !superClass.equals(cls)) {classSet.add(cls);}}return classSet;}/*** 获取应用包名下带有某注解的所有类*/public static Set<Class<?>> getClassSetByAnnotation(Class<? extends Annotation> annotationClass) {Set<Class<?>> classSet = new HashSet<Class<?>>();for (Class<?> cls : CLASS_SET) {if (cls.isAnnotationPresent(annotationClass)) {classSet.add(cls);}}return classSet;}
}
package org.smart4j.framework.helper;import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.smart4j.framework.util.ReflectionUtil;/*** Bean 助手类** @author huangyong* @since 1.0.0*/
public final class BeanHelper {private static final Map<Class<?>, Object> BEAN_MAP = new HashMap<Class<?>, Object>();static {Set<Class<?>> beanClassSet = ClassHelper.getBeanClassSet();for (Class<?> beanClass : beanClassSet) {Object obj = ReflectionUtil.newInstance(beanClass);BEAN_MAP.put(beanClass, obj);}}/*** 获取 Bean 映射*/public static Map<Class<?>, Object> getBeanMap() {return BEAN_MAP;}/*** 获取 Bean 实例*/@SuppressWarnings("unchecked")public static <T> T getBean(Class<T> cls) {if (!BEAN_MAP.containsKey(cls)) {throw new RuntimeException("can not get bean by class: " + cls);}return (T) BEAN_MAP.get(cls);}/*** 设置 Bean 实例*/public static void setBean(Class<?> cls, Object obj) {BEAN_MAP.put(cls, obj);}
}
2、AOP
先将目标类的所有的切面类找出来,链式的将切面代理类作为目标类的增强返回新的bean,替换原来的bean到map中。cglib动态代理生成的代理类在静态代码块中为每个父类方法生成一个MethodProxy代理对象,执行方法时先判断是否需要执行拦截。
引申:事务内嵌套事务(同一个类中)为什么不生效?容器启动时代理类生成,从类外调用方法时调用的是代理类的方法,类内不是(Spring service本类中方法调用另一个方法事务不生效问题)
package org.smart4j.framework.helper;import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.framework.annotation.Aspect;
import org.smart4j.framework.annotation.Service;
import org.smart4j.framework.proxy.AspectProxy;
import org.smart4j.framework.proxy.Proxy;
import org.smart4j.framework.proxy.ProxyManager;
import org.smart4j.framework.proxy.TransactionProxy;/*** 方法拦截助手类** @author huangyong* @since 1.0.0*/
public final class AopHelper {private static final Logger LOGGER = LoggerFactory.getLogger(AopHelper.class);static {try {Map<Class<?>, Set<Class<?>>> proxyMap = createProxyMap();Map<Class<?>, List<Proxy>> targetMap = createTargetMap(proxyMap);for (Map.Entry<Class<?>, List<Proxy>> targetEntry : targetMap.entrySet()) {Class<?> targetClass = targetEntry.getKey();List<Proxy> proxyList = targetEntry.getValue();Object proxy = ProxyManager.createProxy(targetClass, proxyList);BeanHelper.setBean(targetClass, proxy);}} catch (Exception e) {LOGGER.error("aop failure", e);}}private static Map<Class<?>, Set<Class<?>>> createProxyMap() throws Exception {Map<Class<?>, Set<Class<?>>> proxyMap = new HashMap<Class<?>, Set<Class<?>>>();addAspectProxy(proxyMap);addTransactionProxy(proxyMap);return proxyMap;}private static void addAspectProxy(Map<Class<?>, Set<Class<?>>> proxyMap) throws Exception {Set<Class<?>> proxyClassSet = ClassHelper.getClassSetBySuper(AspectProxy.class);for (Class<?> proxyClass : proxyClassSet) {if (proxyClass.isAnnotationPresent(Aspect.class)) {Aspect aspect = proxyClass.getAnnotation(Aspect.class);Set<Class<?>> targetClassSet = createTargetClassSet(aspect);proxyMap.put(proxyClass, targetClassSet);}}}private static void addTransactionProxy(Map<Class<?>, Set<Class<?>>> proxyMap) {Set<Class<?>> serviceClassSet = ClassHelper.getClassSetByAnnotation(Service.class);proxyMap.put(TransactionProxy.class, serviceClassSet);}private static Set<Class<?>> createTargetClassSet(Aspect aspect) throws Exception {Set<Class<?>> targetClassSet = new HashSet<Class<?>>();Class<? extends Annotation> annotation = aspect.value();if (annotation != null && !annotation.equals(Aspect.class)) {targetClassSet.addAll(ClassHelper.getClassSetByAnnotation(annotation));}return targetClassSet;}private static Map<Class<?>, List<Proxy>> createTargetMap(Map<Class<?>, Set<Class<?>>> proxyMap) throws Exception {Map<Class<?>, List<Proxy>> targetMap = new HashMap<Class<?>, List<Proxy>>();for (Map.Entry<Class<?>, Set<Class<?>>> proxyEntry : proxyMap.entrySet()) {Class<?> proxyClass = proxyEntry.getKey();Set<Class<?>> targetClassSet = proxyEntry.getValue();for (Class<?> targetClass : targetClassSet) {Proxy proxy = (Proxy) proxyClass.newInstance();if (targetMap.containsKey(targetClass)) {targetMap.get(targetClass).add(proxy);} else {List<Proxy> proxyList = new ArrayList<Proxy>();proxyList.add(proxy);targetMap.put(targetClass, proxyList);}}}return targetMap;}
}
package org.smart4j.framework.proxy;import java.lang.reflect.Method;
import java.util.List;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;/*** 代理管理器** @author huangyong* @since 1.0.0*/
public class ProxyManager {@SuppressWarnings("unchecked")public static <T> T createProxy(final Class<?> targetClass, final List<Proxy> proxyList) {return (T) Enhancer.create(targetClass, new MethodInterceptor() {@Overridepublic Object intercept(Object targetObject, Method targetMethod, Object[] methodParams, MethodProxy methodProxy) throws Throwable {return new ProxyChain(targetClass, targetObject, targetMethod, methodProxy, methodParams, proxyList).doProxyChain();}});}
}
package org.smart4j.framework.proxy;import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import net.sf.cglib.proxy.MethodProxy;/*** 代理链** @author huangyong* @since 1.0.0*/
public class ProxyChain {private final Class<?> targetClass;private final Object targetObject;private final Method targetMethod;private final MethodProxy methodProxy;private final Object[] methodParams;private List<Proxy> proxyList = new ArrayList<Proxy>();private int proxyIndex = 0;public ProxyChain(Class<?> targetClass, Object targetObject, Method targetMethod, MethodProxy methodProxy, Object[] methodParams, List<Proxy> proxyList) {this.targetClass = targetClass;this.targetObject = targetObject;this.targetMethod = targetMethod;this.methodProxy = methodProxy;this.methodParams = methodParams;this.proxyList = proxyList;}public Object[] getMethodParams() {return methodParams;}public Class<?> getTargetClass() {return targetClass;}public Method getTargetMethod() {return targetMethod;}public Object doProxyChain() throws Throwable {Object methodResult;if (proxyIndex < proxyList.size()) {methodResult = proxyList.get(proxyIndex++).doProxy(this);} else {methodResult = methodProxy.invokeSuper(targetObject, methodParams);}return methodResult;}
}
package org.smart4j.framework.proxy;/*** 代理接口** @author huangyong* @since 1.0.0*/
public interface Proxy {/*** 执行链式代理*/Object doProxy(ProxyChain proxyChain) throws Throwable;
}
package org.smart4j.framework.proxy;import java.lang.reflect.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;/*** 切面代理** @author huangyong* @since 1.0.0*/
public abstract class AspectProxy implements Proxy {private static final Logger logger = LoggerFactory.getLogger(AspectProxy.class);@Overridepublic final Object doProxy(ProxyChain proxyChain) throws Throwable {Object result = null;Class<?> cls = proxyChain.getTargetClass();Method method = proxyChain.getTargetMethod();Object[] params = proxyChain.getMethodParams();begin();try {if (intercept(cls, method, params)) {before(cls, method, params);result = proxyChain.doProxyChain();after(cls, method, params, result);} else {result = proxyChain.doProxyChain();}} catch (Exception e) {logger.error("proxy failure", e);error(cls, method, params, e);throw e;} finally {end();}return result;}public void begin() {}public boolean intercept(Class<?> cls, Method method, Object[] params) throws Throwable {return true;}public void before(Class<?> cls, Method method, Object[] params) throws Throwable {}public void after(Class<?> cls, Method method, Object[] params, Object result) throws Throwable {}public void error(Class<?> cls, Method method, Object[] params, Throwable e) {}public void end() {}
}
package org.smart4j.framework.proxy;import java.lang.reflect.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.framework.annotation.Transaction;
import org.smart4j.framework.helper.DatabaseHelper;/*** 事务代理** @author huangyong* @since 1.0.0*/
public class TransactionProxy implements Proxy {private static final Logger LOGGER = LoggerFactory.getLogger(TransactionProxy.class);private static final ThreadLocal<Boolean> FLAG_HOLDER = new ThreadLocal<Boolean>() {@Overrideprotected Boolean initialValue() {return false;}};@Overridepublic Object doProxy(ProxyChain proxyChain) throws Throwable {Object result;boolean flag = FLAG_HOLDER.get();Method method = proxyChain.getTargetMethod();if (!flag && method.isAnnotationPresent(Transaction.class)) {FLAG_HOLDER.set(true);try {DatabaseHelper.beginTransaction();LOGGER.debug("begin transaction");result = proxyChain.doProxyChain();DatabaseHelper.commitTransaction();LOGGER.debug("commit transaction");} catch (Exception e) {DatabaseHelper.rollbackTransaction();LOGGER.debug("rollback transaction");throw e;} finally {FLAG_HOLDER.remove();}} else {result = proxyChain.doProxyChain();}return result;}
}
3、依赖注入
将类中需要注入bean的属性(可能加了XX注解),反射注入进去
package org.smart4j.framework.helper;import java.lang.reflect.Field;
import java.util.Map;
import org.smart4j.framework.annotation.Inject;
import org.smart4j.framework.util.ArrayUtil;
import org.smart4j.framework.util.CollectionUtil;
import org.smart4j.framework.util.ReflectionUtil;/*** 依赖注入助手类** @author huangyong* @since 1.0.0*/
public final class IocHelper {static {Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();if (CollectionUtil.isNotEmpty(beanMap)) {for (Map.Entry<Class<?>, Object> beanEntry : beanMap.entrySet()) {Class<?> beanClass = beanEntry.getKey();Object beanInstance = beanEntry.getValue();Field[] beanFields = beanClass.getDeclaredFields();if (ArrayUtil.isNotEmpty(beanFields)) {for (Field beanField : beanFields) {if (beanField.isAnnotationPresent(Inject.class)) {Class<?> beanFieldClass = beanField.getType();Object beanFieldInstance = beanMap.get(beanFieldClass);if (beanFieldInstance != null) {ReflectionUtil.setField(beanInstance, beanField, beanFieldInstance);}}}}}}}
}
package org.smart4j.framework.util;import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;/*** 反射工具类** @author huangyong* @since 1.0.0*/
public final class ReflectionUtil {private static final Logger LOGGER = LoggerFactory.getLogger(ReflectionUtil.class);/*** 创建实例*/public static Object newInstance(Class<?> cls) {Object instance;try {instance = cls.newInstance();} catch (Exception e) {LOGGER.error("new instance failure", e);throw new RuntimeException(e);}return instance;}/*** 创建实例(根据类名)*/public static Object newInstance(String className) {Class<?> cls = ClassUtil.loadClass(className);return newInstance(cls);}/*** 调用方法*/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("invoke method failure", e);throw new RuntimeException(e);}return result;}/*** 设置成员变量的值*/public static void setField(Object obj, Field field, Object value) {try {field.setAccessible(true);field.set(obj, value);} catch (Exception e) {LOGGER.error("set field failure", e);throw new RuntimeException(e);}}
}
4、mvc
根据方法上的注解将请求路径、类、方法存入Map<Request, Handler>中
public class Request {/*** 请求方法*/private String requestMethod;/*** 请求路径*/private String requestPath;public Request(String requestMethod, String requestPath) {this.requestMethod = requestMethod;this.requestPath = requestPath;}public String getRequestMethod() {return requestMethod;}public String getRequestPath() {return requestPath;}@Overridepublic int hashCode() {return HashCodeBuilder.reflectionHashCode(this);}@Overridepublic boolean equals(Object obj) {return EqualsBuilder.reflectionEquals(this, obj);}
}
public class Handler {/*** Controller 类*/private Class<?> controllerClass;/*** Action 方法*/private Method actionMethod;public Handler(Class<?> controllerClass, Method actionMethod) {this.controllerClass = controllerClass;this.actionMethod = actionMethod;}public Class<?> getControllerClass() {return controllerClass;}public Method getActionMethod() {return actionMethod;}
}
package org.smart4j.framework.helper;import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.smart4j.framework.annotation.Action;
import org.smart4j.framework.bean.Handler;
import org.smart4j.framework.bean.Request;
import org.smart4j.framework.util.ArrayUtil;
import org.smart4j.framework.util.CollectionUtil;/*** 控制器助手类** @author huangyong* @since 1.0.0*/
public final class ControllerHelper {private static final Map<Request, Handler> ACTION_MAP = new HashMap<Request, Handler>();static {Set<Class<?>> controllerClassSet = ClassHelper.getControllerClassSet();if (CollectionUtil.isNotEmpty(controllerClassSet)) {for (Class<?> controllerClass : controllerClassSet) {Method[] methods = controllerClass.getDeclaredMethods();if (ArrayUtil.isNotEmpty(methods)) {for (Method method : methods) {if (method.isAnnotationPresent(Action.class)) {Action action = method.getAnnotation(Action.class);String mapping = action.value();if (mapping.matches("\\w+:/\\w*")) {String[] array = mapping.split(":");if (ArrayUtil.isNotEmpty(array) && array.length == 2) {String requestMethod = array[0];String requestPath = array[1];Request request = new Request(requestMethod, requestPath);Handler handler = new Handler(controllerClass, method);ACTION_MAP.put(request, handler);}}}}}}}}/*** 获取 Handler*/public static Handler getHandler(String requestMethod, String requestPath) {Request request = new Request(requestMethod, requestPath);return ACTION_MAP.get(request);}
}
然后在DispatcherServlet的service方法解析出来
@Overridepublic void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {ServletHelper.init(request, response);try {String requestMethod = request.getMethod().toLowerCase();String requestPath = request.getPathInfo();Handler handler = ControllerHelper.getHandler(requestMethod, requestPath);if (handler != null) {Class<?> controllerClass = handler.getControllerClass();Object controllerBean = BeanHelper.getBean(controllerClass);Param param;if (UploadHelper.isMultipart(request)) {param = UploadHelper.createParam(request);} else {param = RequestHelper.createParam(request);}Object result;Method actionMethod = handler.getActionMethod();if (param.isEmpty()) {result = ReflectionUtil.invokeMethod(controllerBean, actionMethod);} else {result = ReflectionUtil.invokeMethod(controllerBean, actionMethod, param);}if (result instanceof View) {handleViewResult((View) result, request, response);} else if (result instanceof Data) {handleDataResult((Data) result, response);}}} finally {ServletHelper.destroy();}}
源码包下载:https://download.csdn.net/download/heqinfj/10265752
这篇关于《架构探险从零开始写javaweb》总结的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!