浅谈Aop
什么是Aop
AOP为Aspect Oriented Programming的缩写。
AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
什么是面向切面编程呢?
当我们在编写程序的时候 难免遇到代码冗余(重复)的问题 这个时候你 可以将重复的代码 专门抽取出来形成一个一个小的方法 再将方法写成一个专门的类 那么这个类 就是我们所谓的切面类(这里面保存的是 重复的方法) 在代码执行的时候为了保证 程序能够正常执行 我们需要将重复的代码 植入到程序原来的位置(切入点)上去 这种编程思想 就叫做面向切面编程
使用aop+自定义注解来完成 用户行为记录
1、定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BehaviorLog {
//对当前方法的描述
String description() default "";
//这个表示的是方法的名字
String methodName() default "";
}
2、定义AOP
public class Aop {
/**
* 开始
*/
public void start(JoinPoint joinPoint, BehaviorLog behaviorLog){
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String time = simpleDateFormat.format(new Date());
//调用的方法的名字
String methodName = behaviorLog.methodName();
//这个是方法的描述
String description = behaviorLog.description();
//调用方法传递的参数
Object[] args = joinPoint.getArgs();
System.out.println("张三在"+time+"调用了"+methodName+"传递了"+ Arrays.toString(args)+"参数开始");
//将数据 写入到数据库中
}
/**
* 结束
*/
public void end(JoinPoint joinPoint,BehaviorLog behaviorLog){
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String time = simpleDateFormat.format(new Date());
//调用的方法的名字
String methodName = behaviorLog.methodName();
//这个是方法的描述
String description = behaviorLog.description();
//调用方法传递的参数
Object[] args = joinPoint.getArgs();
System.out.println("张三在"+time+"调用了"+methodName+"传递了"+ Arrays.toString(args)+"参数结束");
//根据用户token去更新这个数据
}
}
3、定义业务类
public class UserService implements IUserService {
/**
* 记录这个用户的行为
*/
@BehaviorLog(description = "添加数据",methodName = "add")
public void add(){
System.out.println("添加数据成功....");
}
}
4、编写配置文件
<!--下面玩的是 aop的配置-->
<bean id="aop" class="com.qf.ibatis.aop1.example.Aop"></bean>
<bean id="userService" class="com.qf.ibatis.aop1.example.UserService"></bean>
<!--下面配置aop-->
<aop:config>
<aop:pointcut id="pt" expression="execution(* com.qf.ibatis.aop1.example.UserService.*(..)) && @annotation(behaviorLog)"></aop:pointcut>
<!--引入切面类-->
<aop:aspect ref="aop">
<!--在这里面进行配置-->
<!--在执行目标方法之前执行-->
<aop:before method="start" pointcut-ref="pt"></aop:before>
<!--在执行了目标方法之后 动态植入下面方法的代码-->
<aop:after method="end" pointcut-ref="pt"></aop:after>
</aop:aspect>
</aop:config>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
5、测试
public static void main(String[] args){
//获取咋们的IOC容器
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:bean-aop-example.xml");
//通过名字 在IOC容器中 获取对象
IUserService userService = (IUserService) context.getBean("userService");
userService.add();
}
6、测试结果
7、遇到问题
这边博主在测试的时候遇到了一个问题。
BeanNotOfRequiredTypeException
后边查阅了资料显示问题是配置文件中的
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
问题和解决方案
//proxy-target-class属性决定是基于接口的还是基于类的代理被创建
//true时基于类的代理被创建
//flase时基于接口的代理被创建
<aop:aspectj-autoproxy proxy-target-class="true"/>