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可得到如下结果