跟我動手搭框架二之AOP實(shí)現(xiàn)

代理這里主要用CGLIB代理,主要為實(shí)現(xiàn)前置通知,后置通知,環(huán)繞通知和異常通知

本篇主要承上啟下,承上根據(jù)IOC容易實(shí)現(xiàn)簡單AOP代理, 啟下,對將要實(shí)現(xiàn)的WEB模塊做一個(gè)規(guī)劃

文章中多有代碼,會在第三部分WEB容器實(shí)現(xiàn),列出參考文檔及GITHUB源碼地址

目錄

  • 1.編寫工具類
  • 2.實(shí)現(xiàn)AOP
  • 3.web實(shí)現(xiàn)規(guī)劃

定義接口類并提供抽象空實(shí)現(xiàn)

抽象目的: 實(shí)現(xiàn)類只需要繼承要,實(shí)現(xiàn)的方法,即可

/**
 * @Package: smile.proxy
 * @Description: 代理通知
 * @author: liuxin
 * @date: 2017/10/18 上午10:18
 */
public interface ProxyAspect {
    /**
     * 前置通知
     */
    void before();
    /**
     * 后置通知
     */
    void after();
    /**
     * 異常通知
     */
    void throwed();
    /**
     * 環(huán)繞通知
     */
    void around();
}
/**
 * @Package: smile.proxy
 * @Description:
 * @author: liuxin
 * @date: 2017/10/18 上午10:22
 */
public abstract class DefaultProxyAspect implements ProxyAspect {
    @Override
    public void before() {}
    @Override
    public void after() {}
    @Override
    public void throwed() {}
    @Override
    public void around() {}
}

定義CGLIBProxy工具

主要邏輯

  • 實(shí)現(xiàn)提供方法級代理,也就是對象不用實(shí)例化
  • 對實(shí)例進(jìn)行代理

代碼更有說服力,直接看注釋

/**
 * @Package: com.example.proxy
 * @Description: JDK自帶動態(tài)代理,只能代理,擁有接口的,而Cglib代理,是運(yùn)行在動態(tài)生成字節(jié)碼的工具中
 * 根據(jù)注解實(shí)現(xiàn)
 * @author: liuxin
 * @date: 17/3/31 上午10:24
 */
public class CGLibProxy implements MethodInterceptor {
    private ProxyAspect proxyAspect;
    private Class cls;
    private Object object;

    /**
     * 預(yù)處理
     * 當(dāng)代理邏輯中依賴其他類,需要提前注入時(shí)候,僅擴(kuò)展此類
     *
     * 擴(kuò)展邏輯類 proxyAspect 從ioc容器中獲取實(shí)例
     *
     * @return
     */
    public List<String> preProcessing() {
        SmileProxyAspect smileProxyAspect = (SmileProxyAspect) cls.getAnnotation(SmileProxyAspect.class);
        try {
            proxyAspect = smileProxyAspect.proxyAspect().newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return Arrays.asList(smileProxyAspect.methods());
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        Object result = null;
        //判斷方法是否使用代理
        boolean contains = preProcessing().contains(method.getName());
        if (contains) {
            proxyAspect.around();
            proxyAspect.before();
            try {
                if (object == null) {
                    result = methodProxy.invokeSuper(obj, args);
                } else {
                    result = methodProxy.invoke(object, args);
                }
            } catch (Throwable throwable) {
                proxyAspect.throwed();
            }
            proxyAspect.after();
            proxyAspect.around();
        } else {
            result = methodProxy.invokeSuper(obj, args);
        }
        return result;
    }


    public static CGLibProxy instance() {
        return new CGLibProxy();
    }


    /**
     * 利用泛型
     * 獲取代理類型
     *
     * @param cls
     * @param <T>
     * @return
     */
    public <T> T getProxy(Class<T> cls) {
        this.cls = cls;
        return (T) Enhancer.create(cls, this);
    }

    /**
     * 獲取代理類
     * @param cls
     * @return
     */
    public Object toProxyObject(Class cls) {
        this.cls = cls;
        return  Enhancer.create(cls, this);
    }

    /**
     * 注入代理對象實(shí)例
     *
     * @param obj
     * @return
     */
    public CGLibProxy setProxyObject(Object obj) {
        this.object = obj;
        return this;
    }

    /**
     * 演示代碼中,均使用@SmileProxyAspect注解實(shí)現(xiàn)
     * 注解中
     * proxyAspect 代理切面類,需要包括處理邏輯 要實(shí)現(xiàn)DefaultProxyAspect 需要實(shí)現(xiàn)的抽象方法
     * methods  需要代理的方法名稱
     *
     * @param args
     */
    public static void main(String[] args) {
        /******************************************
         * 方法級代理
         */
        /**
         * 實(shí)現(xiàn)前置通知和后置通知
         */
        Jay2 proxy1 = CGLibProxy.instance().getProxy(Jay2.class);
        proxy1.dance("芭蕾舞");
        System.out.println(proxy1);
        /**
         * 使用默認(rèn)通知,只打印日志
         */
        Jay2 proxy = CGLibProxy.instance().getProxy(Jay2.class);
        System.out.println(proxy);
        proxy.dance("芭蕾舞");
        /******************************************
         * 實(shí)例代理
         */
        /**
         * 攔截對象
         */
        Jay2 jay2 = CGLibProxy.instance().setProxyObject(new Jay2("周杰倫")).getProxy(Jay2.class);
        jay2.say();
        Jay2 jay3 = CGLibProxy.instance().setProxyObject(new Jay2("周杰倫")).getProxy(Jay2.class);
        jay3.say();
        System.out.println(Jay2.class.isAssignableFrom(jay3.getClass()));
        System.out.println(jay3);
        Object jay4= CGLibProxy.instance().setProxyObject(new Jay2("周杰倫")).toProxyObject(Jay2.class);

    }
}

AOP實(shí)現(xiàn)

  • 實(shí)現(xiàn)方案

    當(dāng)IOC容器掃描所有被@SmileComonpent標(biāo)記的組件時(shí)候,會判斷是否被@SmileProxyAspect 注解修飾,

    如果有@SmileProxyAspect,則對實(shí)例化對象生成代理,注入

/**
     * 掃描所有被標(biāo)記的組件
     */
    public void scanComponent(Class<?> nextCls) {
        SmileComponent declaredAnnotation = nextCls.getDeclaredAnnotation(SmileComponent.class);
        Object beanInstance = null;
        beanInstance = nextCls.newInstance();
       //判斷是否包括代理注解,如過包括就生成代理對象
        SmileProxyAspect smileProxyAspect = (SmileProxyAspect) nextCls.getAnnotation(SmileProxyAspect.class);
        if (smileProxyAspect != null) {        beanInstance=CGLibProxy.instance().setProxyObject(beanInstance).toProxyObject(nextCls);   
      ....
      ....
       registeredBeans.put(beanName, new BeanDefinition(nextCls, beanInstance));
               
    }

3. web規(guī)劃

在對ioc容器及代理編寫完成后,就到重點(diǎn)我們要實(shí)現(xiàn),對HTTP請求的解析和處理. 在此實(shí)現(xiàn),要對項(xiàng)目做一個(gè)規(guī)劃,打一個(gè)草稿

項(xiàng)目基于Maven多模塊實(shí)現(xiàn)

3.1 包名

groupId: org.smileframework.boot

artifactId:

  • org.smileframework.web
  • org.smileframework.tool
  • org.smileframework.data
  • org.smileframework.ioc

3.2TOOLS部分

工欲善其事必先利其器,所以先寫我們將會遇到的工具類

  • 生成代理部分 CGLIB代理 org.smileframework.tool.proxy
  • 線程工廠及拒絕策略 org.smileframework.tool.threadpool
  • json及xml轉(zhuǎn)換 org.smileframework.tool.json | .xml
  • 數(shù)據(jù)流工具類 org.smileframework.tool.io
  • 類加載器器 org.smileframework.tool.clazz
  • 文件讀取工具 org.smileframework.tool.io.SmileClassPathResource

3.3 IOC部分

在處理器中掃描注解可以知道項(xiàng)目具有哪些功能
@SmileBootApplication 如果有改掃描器,就到子目錄中的使用@SmileComponent注解的都加入到默認(rèn)的beans容器中
然后開始實(shí)例化,如果發(fā)現(xiàn)Class中包括@InsertBean()將從bean容器中的對象,反射進(jìn)去生成對象.發(fā)現(xiàn)方法中用@SmileBean修飾的同樣從ioc容器中獲取實(shí)例,并注入到該對象中,最終保存到IOC容器

3.4 合并WEB上下文

從bean容器中獲取到ExtApplicationContext

3.5 綁定Url和處理類

@GetMapping 標(biāo)記get請求方法
@PostMapping 標(biāo)記post請求方法
@RequestBody 將請求體綁定到方法指定類型
@RequestHander 綁定請求頭到被就是的map類型
@RequestParam 指定方法請求參數(shù)名

WebDefinition webDefinition = WebContextTools.getWebDefinitionByUrl(dispatchUrl, requestMethod);

校驗(yàn)使用反射,將該方法的參數(shù)名稱和請求到的參數(shù)做一個(gè)簡單校驗(yàn)
//測試將POST請求體中數(shù)據(jù),反序列化為User
@PostMapping(value = "/smile/test/requestBody", consumes.., produces..)
public String testRequestBody(@RequestBoby UserDto user) {
    return user.getName() + "--" + user.getAge();
}

//Method: 獲取到的執(zhí)行方法 parameters:請求參數(shù) headers:請求頭
//將以上信息根據(jù)consumes定義的解析方法,轉(zhuǎn)換成方法指定類型
Object[] args = ControllerUtils.getArgs(method, parameters,headers);
Object invokeResult = method.invoke(controller, args);
//根據(jù)produces定義的返回值類型,通過Netty channle返回給客戶端


3.6 AOP 攔截

在掃描時(shí)候找到切面類,讀取里面的class類型

proxyAspect: 代理邏輯,實(shí)現(xiàn) 1.前置 2. 后置 3.環(huán)繞 4.異常通知

@SmileProxyAspect(proxyAspect = ControllerProxyAspectDemo.class, methods = {"testRequestBody", "testRequestParam"})

獲取到這個(gè)注解,并獲取class類型,從bean容器中,獲取這個(gè)對象(A),根據(jù)Smile的方法把這個(gè)A對象,進(jìn)行代理.

3.7 web容器使用Netty

  • 定義WebApplicationContext 類實(shí)現(xiàn)ExtApplicationContext上下文信息獲取IOC容器,并掃描ioc獲取url綁定handler綁定的信息
  • 創(chuàng)建netty server端
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容