通俗易懂理解 面向切面编程(AOP)

      面上切面编程,听起来就是一个十分难懂的词。在网上看了许多的解释,现在给大家谈谈我对AOP的理解。

      首先我们看看aop解决了什么问题:

         

我们就举个例子 从事务处理的层面来解释AOP

比如我们现在要做一个 ATM机 的系统。

假设流程图如下:

我们可以发现,验证用户的代码明显重复了,这明显不符合我们 低耦合高内聚 的思想。

于是aop就起作用了

我们可以写一个验证用户的类,然后依次跟取款,查询,转账绑定,就不用费事的写三遍了。为什么说是面向切面,因为我们从图中可以看出,验证用户这一条线,切 了取款,查询,转账的操作。

具体我们可以用简单的代码来实现一下:

xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
 <!-- 注解形式 开启aop -->
  <aop:aspectj-autoproxy ></aop:aspectj-autoproxy>
  
  <!-- 创建对象 -->
     <bean id="User" class="cn.itcast.aop.User"></bean>
       <bean id="Verification" class="cn.itcast.aop.Verification"></bean>
  
        
        
</beans>

User.java

package cn.itcast.aop;

public class User {
  
	
	public void Withdraw() {
		
		System.out.println("我要取一个亿,有钱任性");

	}
	
	 public  void query() 
      {
	 System.out.println("我要 查 我还有多少钱");
      }
}

Verification.java

package cn.itcast.aop;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
//@Component(value="user") 对象注解
//aop注解
//Transactional 事务注解

@Aspect  //切面
public class Verification {
     @Before(value = "execution(* cn.itcast.aop.User.*(..))")//表示User内所有的方法 都要验证
	 public void before1(){
	         System.out.println("我要验证你 是不是我的用户");
		 System.out.println("|");
		 System.out.println("V");
		 
	 }
}

结果:

我们可以看到,我们已经实现了AOP。

大致可以理解为:

看完这些,有没有对AOP有 更进一步的认识和理解呢?

发布了69 篇原创文章 · 获赞 5 · 访问量 2229

猜你喜欢

转载自blog.csdn.net/qq_42139889/article/details/103216018