当前位置: 移动技术网 > IT编程>开发语言>Java > Spring面向切面编程AOP

Spring面向切面编程AOP

2020年07月31日  | 移动技术网IT编程  | 我要评论

AOP(Aspect Oriented Programming):面向切面编程

利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。即不通过修改源代码方式,在主干功能里面添加源代码。

aop使用简单说明

1. AOP底层原理

1.1 AOP底层使用动态代理
  • 有接口情况,使用JDK动态代理
    创建接口实现类代理对象,增强类的方法
    JDK动态代理
1.1.1 JDK动态代码底层实现

Class Proxy----newProxyInstance(ClassLoader loader,类<?>[] interfaces,InvocationHandle h)方法:返回指定接口的代理类的实例
ClassLoader loader:类加载器
Class<?>[] interfaces:增强方法所在的类,这个类实现接口,支持多个接口
InvocationHandle:实现这个接口InvocationHandle,创建代理对象,写增强部分

(1)创建接口,定义方法

package com.company; public interface UserDao { public int add(int a,int b); public String upadte(String id); } 

(2)创建接口实现类,实现方法

package com.company; public class UserDaoImpl implements UserDao{ @Override public int add(int a, int b) { System.out.println("add方法被执行"); return a+b; } @Override public String upadte(String id) { System.out.println("update方法被执行"); return id; } } 

(3)使用Proxy类创建代理对象

package com.company; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Arrays; public class JDKProxy { public static void main(String[] args) { //创建接口实现类代理对象 Class[] interfaces={UserDao.class}; //匿名内部类实现InvocationHandler /*Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                return null;
            }
        });*/ //有参构造传递对象,先new对象 UserDaoImpl userDao=new UserDaoImpl(); UserDao dao=(UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(),interfaces,new UserDaoProxy(userDao)); int result=dao.add(1,2); System.out.println("result:"+result); } } //创建代理对象代码 class UserDaoProxy implements InvocationHandler{ //把创建的时谁的代理对象,将其传递过来 //有参构造传递 private Object obj; public UserDaoProxy(Object obj){ this.obj=obj; } //增强逻辑 @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //方法之前的处理 System.out.println("方法之前执行..."+method.getName()+",传递的参数:"+Arrays.toString(args)); //被增强的方法执行 Object res=method.invoke(obj,args); //可通过method.getName()判断方法,从而执行不同增强操作 //方法之后的处理 System.out.println("方法之后执行..."+obj); return null; } } 
  • 没有接口情况,使用CGLIB动态代理
    CGLIB动态代理

2. AOP术语

  • 连接点
    类里面哪些方法可以被增强,则这些方法就是连接点。

  • 切入点
    实际被真正增强的方法,就是切入点。

  • 通知(增强)
    实际增强的逻辑部分称为通知(增强),主要具有以下五种类型:
    前置通知,后置通知,环绕通知,异常通知,最终通知

  • 切面
    把通知应用到切入点的过程。

3. AOP操作

Spring框架中一般基于AspectJ实现AOP操作。

3.1 什么时AspectJ

AspectJ不是Spring的组成部分,是独立的AOP框架,一般把AspectJ和Spring框架一起使用,进行AOP操作。

3.2 基于AspectJ实现AOP操作

(1) 引入AOP相关依赖:
com.springsource.net.sf.cglib-2.2.0.jarcom.springsource.org.aopalliance-1.0.0.jarcom.springsource.org.aspectj.weaver-1.6.8-RELEASE.jarspring-aspects-5.2.6.RELEASE.jar
(2) 切入点表达式
切入点表达式的作用:知道对哪个类里面的哪个方法进行增强。
语法结构:
execution([权限修饰符][返回类型][类全路径][方法名称]([参数列表]))
示例1:对com.atguigu.dao.BookDao类里的add方法进行增强:
execution(* com.atguigu.dao.BookDao.add(..))
示例2:对com.atguigu.dao.BookDao类里的所有方法进行增强:
execution(* com.atguigu.dao.BookDao.*(..))

3.2.2 基于注解方式

(1)创建类,在类里面定义方法

package com.company.aopanno; import org.springframework.stereotype.Component; //被增强的类 @Component public class User { public void add(){ System.out.println("add...."); } } 

(2)创建增强类,编写增强逻辑,创建方法,让不同的方法代表不同的通知类型

  • 在Spring配置文件中,开启注解扫描
  • 使用注解创建User和UserProxy对象
  • 在增强类上面添加注解@Aspect
  • 在Spring配置文件中开启代理对象

开启注册扫描:

<?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:context="http://www.springframework.org/schema/context" 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/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!--开启注解扫描--> <context:component-scan base-package="com.company.aopanno"></context:component-scan> <!--开启AspectJ生成代理对象--> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans> 
package com.company.aopanno; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; //增强类 @Component @Aspect //生成代理对象 public class UserProxy { //前置通知 //@Before注解表示作为前置通知 @Before(value = "execution(* com.company.aopanno.User.add(..))") public void before(){ System.out.println("before..."); } //最终通知,表示在方法之后执行 @After(value = "execution(* com.company.aopanno.User.add(..))") public void after(){ System.out.println("after..."); } //后置通知(返回通知),在方法返回值之后执行 @AfterReturning(value = "execution(* com.company.aopanno.User.add(..))") public void afterReturning(){ System.out.println("afterReturning..."); } //异常通知 @AfterThrowing(value = "execution(* com.company.aopanno.User.add(..))") public void afterThrowing(){ System.out.println("afterThrowing...."); } //环绕通知 @Around(value = "execution(* com.company.aopanno.User.add(..))") public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{ System.out.println("环绕之前"); //被增强的方法执行 proceedingJoinPoint.proceed(); System.out.println("环绕之后"); } } 

测试结果:

环绕之前
before...
add....
环绕之后
after...
afterReturning... 

(3)将相同的切入点进行抽取

 //相同切入点抽取 @Pointcut(value = "execution(* com.company.aopanno.User.add(..))") public void pointdemo(){ } //表达式使用方法名替代 @After(value = "pointdemo()") public void after(){ System.out.println("after..."); } 

(4)同一个方法被多个增强类进行增强,设置增强类优先级
使用注解@Order(),括号内数字越小,优先级越高

@Component @Aspect @Order(1) //多个增强类对同一方法进行增强,数字越小优先级越高 public class PersonProxy { @Before(value = "execution(* com.company.aopanno.User.add(..))") public void personBefore(){ System.out.println("Person Before..."); } } @Component @Aspect //生成代理对象 @Order(3) public class UserProxy { //前置通知 //@Before注解表示作为前置通知 @Before(value = "execution(* com.company.aopanno.User.add(..))") public void before(){ System.out.println("before..."); } } 

测试结果:

Person Before...
before... 

(5)若使用完全注解开发,则只需创建配置类,不需创建xm配置文件

@Configuration @ComponentScan(basePackages = {"com.company.aopanno"}) @EnableAspectJAutoProxy(proxyTargetClass = true) //与<aop:aspectj-autoproxy></aop:aspectj-autoproxy>语句一致 public class ConfigAop { } 
3.2.3 基于xml配置文件方式

(1)创建两个类,增强类和被增强类

public class Book { public void buy(){ System.out.println("book..."); } } ---- public class BookProxy { public void before(){ System.out.println("before buy..."); } } 

(2)在Spring配置文件中创建两个类对象
(3)在Spring配置文件中配置切入点

<?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"> <!--创建对象--> <bean id="book" class="com.company.aopxml.Book"></bean> <bean id="bookProxy" class="com.company.aopxml.BookProxy"></bean> <!--配置aop增强--> <aop:config> <!--切入点--> <aop:pointcut id="p" expression="execution(* com.company.aopxml.Book.buy(..))"/> <!--配置切面--> <aop:aspect ref="bookProxy"> <!--配置增强作用在具体的方法上--> <aop:before method="before" pointcut-ref="p"/> </aop:aspect> </aop:config> </beans> 

本文地址:https://blog.csdn.net/weixin_43022687/article/details/107700547

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网