Spring之手寫Aop(1)

aop,面向切面編程,是面向對象的一種補充,手寫之前請確保有一下基礎知識,分別爲java註解的基本使用,java動態代碼,瞭解spring框架,瞭解beanPostProcessor的作用,以及掌握java的適配器模式。

爲了簡化開發量,這裏藉助spring。開發的出的框架遵守aop聯盟,實現方法與spring自帶的Aop實現方式略有不同,但原理相同

在實現方面,另闢道路,通過註解的方式表明 該類需要添加的額外邏輯,話不多說,直接上代碼,先介紹一下涉及的兩個註解

EnableAop : 表明該類開啓切面功能,標有該註解的類將會被系統感知,從而爲其開啓動態代理功能

InterceptorAdvice:作用於方法層面,標有該註解的方法意味着,該方法將被代理,代理方式與spring原生AOp代碼方式相似

爲了便於各位對後面的代碼理解,這裏先讓各位看一下例子


 

package com.example;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

 

/**

* Created by zoujianglin

* 2018/8/29 0029.

*/

public class AopTest {

 

public static void main(String[] args) {

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

UserDao userDao = (UserDao) applicationContext.getBean("userDao");

 

userDao.test();

 

}

 

}

而userDao 的實現者爲


 

package com.example;

 

import com.annotations.EnableAop;

import com.annotations.InterceptorAdvice;

import org.springframework.stereotype.Component;

 

/**

* Created by zoujianglin

* 2018/8/29 0029.

*/

@Component("userDao")

@EnableAop

public class UserDaoImp implements UserDao {

 

@InterceptorAdvice(advices = {MyMethodBeforeAdvice.class,

MyAfterReturnAdvice.class})

public void test() {

System.out.println(" test方法 ");

}

}

接口userDao的定義


 

package com.example;

 

import com.annotations.EnableAop;

import com.annotations.InterceptorAdvice;

import com.autoproxy.Adapter.MethodBeforeAdvice;

 

/**

* Created by zoujianglin

* 2018/8/29 0029.

*/

public interface UserDao {

 

void test();

}

MyMethodBeforeAdvice的實現如下


 

package com.example;

 

import com.autoproxy.Adapter.MethodBeforeAdvice;

 

import java.lang.reflect.Method;

 

/**

* Created by zoujianglin

* 2018/8/29 0029.

*/

public class MyMethodBeforeAdvice implements MethodBeforeAdvice {

public void before(Method method, Object[] args, Object target) throws Throwable {

System.out.println("在方法之前被調用");

}

}

MyAfterReturnAdvice 的實現如下


 

package com.example;

 

import com.autoproxy.Adapter.AfterReturningAdice;

import com.sun.org.apache.xpath.internal.SourceTree;

 

import java.lang.reflect.Method;

 

/**

* Created by zoujianglin

* 2018/8/29 0029.

*/

public class MyAfterReturnAdvice implements AfterReturningAdice {

public void after(Method method, Object[] args, Object target) throws Throwable {

System.out.println("執行在方法運行之後");

}

}

運行AopTest可得到如下結果

​​​​​​​

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章