您的位置:首页 > 编程语言 > Java开发

SpringAop 原理

2021-05-13 15:21 651 查看

著名的spring两大杀手锏:IOC 和 AOP,今天来说下AOP。

缘起:

AOP:面向切面编程,是独立于spring的。spring Aop是AOP的实现框架 
之一。

Spring Aop

说Spring Aop之前有必要说下动态代理(大家都知道代理有两种方式:
静态代理和动态代理),动态代理(JDK实现方式)涉及的四个概念:
目标对象、代理对象、InvocatoinHandler接口、Proxy类。直接上代码:

处理器类:
public class MyInvocationHandler implements InvocationHandler{

//目标对象
private Object target;

private IUserServiceManager userServiceManager;

public MyInvocationHandler(Object target,IUserServiceManager userServiceManager){
    this.target = target;
    this.userServiceManager = userServiceManager;
}

/**
 * 调用
 * @param proxy 代理对象
 * @param method 目标方法
 * @param args 目标方法参数
 * @return
 * @throws Throwable
 */
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

    //非核心代码
    userServiceManager.before();
    //核心业务代码
    Object result = method.invoke(target,args);
    //非核心代码
    userServiceManager.after();
    return result;
}

}

增强类接口:
public interface IUserServiceManager {

public void before();

public void after();

}
增强类实现:
public class UserServiceManagerImpl implements IUserServiceManager{

private ThreadLocalthreadLocal = new ThreadLocal();

@Override
public void before() {
    long nowTimeSeconds= System.currentTimeMillis();
    threadLocal.set(nowTimeSeconds);
    System.out.println("UserServiceManagerImpl before-->time:"+
            nowTimeSeconds);
}

@Override
public void after() {
    long nowTimeSeconds2= System.currentTimeMillis();
    System.out.println("UserServiceManagerImpl after-->time:"+
            nowTimeSeconds2);
    System.out.println("UserServiceManagerImpl 方法耗时:"+
            (threadLocal.get()-nowTimeSeconds2));
}

}
目标类:
public class UserServiceImpl implements IUserService{
@Override
public void add() {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(“UserServiceImpl add…”);
}
}

测试类:
@RunWith(SpringRunner.class)
@ContextConfiguration
public class JDKProxyTest {

@Test
public void jdkProxyTest(){

    //生成一个目标对象
    IUserService target = new UserServiceImpl();

    //增强对象
    IUserServiceManager userServiceManager = new UserServiceManagerImpl();

    //生成一个handler
    MyInvocationHandler handler = new MyInvocationHandler(target,userServiceManager);
    //使用JDK生成代理对象
    IUserService userService = (IUserService) Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),handler);
    //代理对象执行目标方法
    userService.add();

}

@Test
public void springAopTest(){
    ApplicationContext ctx = new AnnotationConfigApplicationContext(AopProxyConfig.class);

// 第二种方式ctx
// AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
// ctx.register(AopProxyConfig.class);
// ctx.refresh();
IUserService userService = (IUserService) ctx.getBean(“userServiceImpl”);
userService.add();
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: