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

​​​​​​​

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值