spring框架之AOP(面向切面编程)

一、AOP简述

AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护(增强方法)的一种技术。

AOP是OOP(面向对象编程)的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间耦合度降低,提高程序的可重用性同时提高了开发的效率

AOP采取横向抽取机制,取代了传统纵向继承体系重复性代码

经典应用:事务管理性能监视、缓存、日志,权限管理

Spring AOP使用纯Java实现,不需要专门的编译过程和类加载器,在运行期通过代理方式向目标类织入增强代码

AspectJ是一个基于Java语言的AOP框架,Spring2.0开始,Spring AOP引入对Aspect的支持,AspectJ扩展了Java语言,提供了一个专门的编译器,在编译时提供横向代码的织入

二、AOP实现原理

aop底层将采用代理机制进行实现。(动态代理模式)

 动态代理它可以直接给某一个目标对象生成一个代理对象,而不需要代理类存在。

动态代理与代理模式(静态代理)原理是一样的,只是它没有具体的代理类,直接通过反射生成了一个代理对象。

①:jdk的动态代理方式(spring的aop底层默认使用的是jdk动态代理)

要求:接口 + 实现类

spring底层默认使用该方式创建代理对象

②: cglib方式

要求:实现类(给目标类创建一个子类)

spring 可以使用cglib字节码增强实现aop。

三、AOP术语

1.target:目标类,需要被代理的类。例如:UserService的实现类UserServiceImpl

2.Joinpoint(连接点):所谓连接点是指那些可能被拦截到的方法。例如:UserServiceImpl所有的方法

3.PointCut 切入点:已经被增强的连接点。例如:addUser()

4.advice 通知/增强,增强代码。例如:after、before

5. Weaving(织入):是指把增强advice应用到目标对象target来创建新的代理对象proxy的过程.

6.proxy 代理类(类似中介)

7. Aspect(切面): 是切入点pointcut和通知advice的结合

四、实现AOP的方式

1、JDK动态代理

 JDK动态代理对“装饰者”设计模式简化。使用前提:必须有接口

目标类:接口 + 实现类(被代理的类需要增强的)

通知类:用于存通知 MyAdvice

工厂类:编写工厂生成代理

主要的两个方法:

Proxy.newProxyInstance():产生代理类的实例。仅能代理实现至少一个接口的类

       ClassLoader:类加载器。固定写法,和被代理类使用相同的类加载器即可。

       Class[] interface:代理类要实现的接口。固定写法,和被代理类使用相同的接口即可。

       InvocationHandler:策略(方案)设计模式的应用。

InvocationHandler中的invoke方法:调用代理类的任何方法,此方法都会执行   

         Object proxy:代理对象本身的引用。一般用不着。

         Method method:当前调用的方法。

         Object[] args:当前方法用到的参数

主要的代码:

public interface ZuFangZi {
  public void lookHouse();
  public void getMoney(double money);
}

FangDong.java

package com.tf.staticproxy;
public class FangDong implements ZuFangZi {
	@Override
	public void lookHouse() {
		System.out.println("看房东的房子");
	}
	@Override
	public void getMoney(double money) {
	System.out.println("房东收到的房租:"+money);
	}
}

CreateZhongjie.java

package com.tf.jdkproxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//创建代理对象
public class CreateZhongJie {
	
public static ZuFangZi createZhongJie(){
	//创建被代理对象(目标类)
     FangDong fangDong = new FangDong();
	/*创建代理 对象
	 * loader:类加载器
	 * interfaces:被代理对象实现的接口列表
	 * h:调用代理对象方法的处理器
	 * */
	return (ZuFangZi) Proxy.newProxyInstance(CreateZhongJie.class.getClassLoader(), fangDong.getClass().getInterfaces(), new InvocationHandler() {
	/*proxy - 在其上调用方法的代理实例   一般用不到
      method - 对应于在代理实例上调用的接口方法的 Method 实例。Method 对象的声明类将是在其中声明方法的接口,
                                      该接口可以是代理类赖以继承方法的代理接口的超接口。
      args - 包含传入代理实例上方法调用的参数值的对象数组,如果接口方法不使用参数,则为 null。
                               基本类型的参数被包装在适当基本包装器类(如 java.lang.Integer 或 java.lang.Boolean)的实例中。 
	 * */
		@Override
		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		System.out.println("中介开始:"+method.getName());
		//扩展代理类
		Double zhongjieMoney = 3000.0;
		Object obj = null;
		if(method.getName().equals("getMoney")){
			Double money = (Double)args[0];
			System.out.println("中介收取:"+zhongjieMoney+"费");
			//通过反射调用目标类的方法
			method.invoke(fangDong, new Double[]{money-zhongjieMoney});
		}else{
			 obj  = method.invoke(fangDong, args);
		}
		   System.out.println("中介开始:"+method.getName()+"结束");
			return obj;
		}
	});	
}
}

Test.java

public class Test {
	public static void main(String[] args) {
		//获得创建的中介类
		ZuFangZi zhongjie = CreateZhongJie.createZhongJie();
		zhongjie.lookHouse();
		zhongjie.getMoney(10000);
	}
} 

 

2、CGLIB字节码增强

当没有接口时,还想生成代理类。

①:没有接口,只有实现类。

②:采用字节码增强框架 cglib,在运行时创建目标类的子类,从而对目标类进行增强。

                                                           目标类:  BokServiceImpl.java

public class BookServiceImpl  {
	public  void add() {
		//开启事务
		try{
		System.out.println("add");
	 }catch (Exception e) {
		//回滚事务
	}
	}
	public  void delete() {
		//开启事务
		try {
		System.out.println("delete");
		//提交事务
		}catch (Exception e) {
			//回滚事务
		}
	}
	}

                                                                         通知类:MyAdvice.java

public class MyAdvice {
	public   void before() {
		System.out.println("前置通知---开启事务");
	}
	public void after() {
		System.out.println("后置通知-----提交事务");
	}
	public void exceptionAdvice() {
		System.out.println("异常通知----回滚事务");
	}
}

                                              工厂类 :MyCglibProxyFactory.java

public class MyCglibProxyFactory {
public static BookServiceImpl createProxy(){
	//1:创建目标类的对象
	BookServiceImpl bookServiceImpl = new BookServiceImpl();
   // 2 创建cglib的核心对象
	Enhancer enhancer  =new Enhancer();
	//3 创建增强类的 对象
	MyAdvice advice = new MyAdvice();
	//4 创建enhancer 父类 
	enhancer.setSuperclass(bookServiceImpl.getClass());
	//5 设置回调函数  通过代理对象调用方法时会执行回调函数中的 MethodInterceptor方法
	enhancer.setCallback(new MethodInterceptor(){
		@Override
		public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
			advice.before();
			Object o  = null;
			try {
			//通过反射调用目标类的方法
			o = method.invoke(bookServiceImpl, args);
			advice.after();
		} catch (Exception e) {
			advice.exceptionAdvice();
		}	 
	     return o;//目标类的返回值
		}
	});
    //6 创建这个代理对象
	return (BookServiceImpl) enhancer.create();
}
}

                                                                         测试类:TestCglib.java

//cglib创建对象,不需要有接口 只要有一个类
public class TestCglib {
public static void main(String[] args) {
	BookServiceImpl b = MyCglibProxyFactory.createProxy();
	b.add();
	b.delete();
   //被增强的方法为切入点
}
}

五、SpringAOP联盟通知类型

  1. AOP联盟为通知Advice定义了org.aopalliance.aop.Advice接口
  2. Spring按照通知Advice在目标类方法的连接点位置,可以分为5类
    • 前置通知 org.springframework.aop.MethodBeforeAdvice
    • 在目标方法执行前实施增强
    • 后置通知org.springframework.aop. AfterReturningAdvice
      • 在目标方法执行后实施增强
    • 环绕通知org.aopalliance.intercept.MethodInterceptor
      • 在目标方法执行前后实施增强
    • 异常抛出通知org.springframework.aop.ThrowsAdvice
      • 在方法抛出异常后实施增强
    • 引介通知 org.springframework.aop.IntroductionInterceptor

在目标类中添加一些新的方法和属性

环绕通知,必须手动执行目标方法放行

try{

   //前置通知

   //执行目标方法

   //后置通知

} catch(){

   //抛出异常通知

}

六、spring编写代理:半自动(了解)

  1. 让spring 创建代理对象,从spring容器(配置文件)中手动的获取代理对象

                                                          增强类

public class MyAdvice implements MethodInterceptor,MethodBeforeAdvice,AfterReturningAdvice {
	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		/*环绕通知 调用目标方法前后都会执行
		 * 是否放行(调用)*/
		System.out.println("环绕通知   ---  后置通知");
		//调用目标方法
	    Object o =	invocation.proceed();
		System.out.println("环绕通知   --- 后置通知");
		return o;
	}
	@Override
	public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
		System.out.println("afterReturning 后置通知");
	}
	@Override
	public void before(Method returnValue, Object[] args, Object target) throws Throwable {
		System.out.println("前置通知");
		
	}
}

                                          spring-di.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- spring的半自动 -->
<!-- 目标类 -->
<bean id="bookService" class="com.tf.aop.banzidong.BookServiceImpl"></bean>
<!-- 通知类的对象 -->
<bean id="myAdvice" class="com.tf.aop.banzidong.MyAdvice"></bean>
<!-- 使用spring的ProxyFactoryBean类创建代理对象 -->
<bean id="myProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interfaces" value="com.tf.aop.banzidong.BookService"></property>
<property name="target" value="bookService"></property>
<property name="interceptorNames" value="myAdvice"></property>
</bean>
</beans>

注意: 这三个名字不能变

interfaces: 被代理对象实现的列表

 target:目标对象的引用

 inteceptorNames:增强类的引用

optimize :强制使用cglib

                <property name="optimize" value="true"></property>

底层机制

            如果目标类有接口,采用jdk动态代理(默认)

            如果没有接口,采用cglib字节码增强

            如果声明 optimize = true ,无论是否有接口,都采用cglib

                                                                             测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:com/tf/aop/banzidong/spring-di.xml")
public class TestBanZiDong {
//spring干一半,我们自己做一半
//提供接口实现类 、通知类
    @Autowired
	private BookService bookService;
	@Test
	public void test() {
    System.out.println(bookService);
	}
}

七、spring aop编程:全自动【掌握】

  1. 从spring容器获得目标类,如果配置aop,spring将自动生成代理。
  2.  要确定目标类,aspectj 切入点表达式、
  3. 导包

    aspectjweaver-1.8.2.jar

    spring-aspects-4.3.5.RELEAxcxcSE.jar

        使用<aop:config>进行配置

                proxy-target-class="true" 声明时使用cglib代理

            <aop:pointcut>切入点,从目标对象获得具体方法

            <aop:advisor>特殊的切面,只有一个通知和一个切入点

                advice-ref通知引用

                pointcut-ref切入点引用   

                                                                      增强类


public class MyAdvice implements MethodInterceptor,MethodBeforeAdvice,AfterReturningAdvice {
	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		/*环绕通知 调用目标方法前后都会执行
		 * 是否放行(调用)*/
		System.out.println("环绕通知   ---  后置通知");
		//调用目标方法
	    Object o =	invocation.proceed();
		System.out.println("环绕通知   --- 后置通知");
		return o;
	}
	@Override
	public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
		System.out.println("afterReturning 后置通知");
	}
	@Override
	public void before(Method returnValue, Object[] args, Object target) throws Throwable {
		System.out.println("前置通知");
		
	}
}

                                                                                             spring-di.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:aop="http://www.springframework.org/schema/aop"
   
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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">
<!-- spring的全自动 -->
<bean id="bookService" class="com.tf.aop.auto.BookServiceImpl"></bean>
<bean id="myAdvice" class="com.tf.aop.auto.MyAdvice"></bean>
<!-- 全自动配置 
解析到aop节点 会为目标类自动创建代理对象那个
-->
<aop:config>
  <aop:pointcut expression="execution(* com.tf.aop.auto.*Impl.*(..))" id="mypointcut"/>
  <aop:advisor advice-ref="myAdvice" pointcut-ref="mypointcut"/>
</aop:config>
</beans>

                                                                                Test测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:com/tf/aop/auto/spring-di.xml")
public class TestAuto {
	@Resource
	private BookService bookService;
	@Test
	public void test(){
		bookService.add();
	}
}

7、2 切入点表达式

.execution()  用于描述方法   @annotation()  描述注解

       语法:execution(修饰符返回值包.类.方法名(参数) throws异常

              修饰符,一般省略

                     public            公共方法

                     *                   任意

              返回值,不能省略

                     void               返回没有值

                     String            返回值字符串

                     *                   任意

              包,[省略]

                     com.qf.crm                   固定包

                     com.qf.crm.*.service     crm包下面子包任意包下的service包(例如:com.qf.crm.staff.service)

                     com.qf.crm..                 crm包下面的所有子包(含自己)

                     com.qf.crm.*.service..   crm包下面任意子包,固定目录service,service目录任意包

                     com.qf.crm.*

              类,[省略]

                     UserServiceImpl                  指定类

                     *Impl                                  以Impl结尾

                     User*                                  以User开头

                     *                                        任意

              方法名,不能省略

                     addUser                               固定方法

                     add*                                          以add开头

                     *Do                                    以Do结尾

                     *                                        任意

              (参数)

                     ()                                        无参

                     (int)                                    一个整型

                     (int ,int)                              两个

                     (..)                                      参数任意

              throws ,可省略,一般不写。

比如execution(* com.tf.aop.auto.*Impl.*(..))    :com.tf.aop.auto包下以Impl结尾的类的任意方法

八、AspectJ介绍

  1. AspectJ是一个基于Java语言的AOP框架
  2. Spring2.0以后新增了对AspectJ切点表达式支持
  3. @AspectJ 是AspectJ1.5新增功能,通过JDK5注解技术,允许直接在Bean类中定义切面

    新版本Spring框架,建议使用AspectJ方式来开发AOP

  1. 主要用途:自定义开发

8、1 AspectJ 通知类型

  1. aspectj 通知类型,只定义类型名称。已知方法格式。
  2. 个数:6种(环绕比较重要)。

       before:前置通知(应用:各种校验)

              在方法执行前执行,如果通知抛出异常,阻止方法运行

       afterReturning:后置通知(应用:常规数据处理)

              方法正常返回后执行,如果方法中抛出异常,通知无法执行

              必须在方法执行后才执行,所以可以获得方法的返回值。

       around:环绕通知(应用:十分强大,可以做任何事情)

              方法执行前后分别执行,可以阻止方法的执行

              必须手动执行目标方法

       afterThrowing:抛出异常通知(应用:包装异常信息)

              方法抛出异常后执行,如果方法没有抛出异常,无法执行

       after:最终通知(应用:清理现场)

              方法执行完毕后执行,无论方法中是否出现异常

环绕

 

try{

     //前置:before

    //手动执行目标方法

    //后置:afterRetruning

} catch(){

    //抛出异常 afterThrowing

} finally{

    //最终 after

}

代码:

                                                  增强类(通知名称任意(方法名任意

/*JoinPoint 可以得到目标类的相关信息
 * ProceedingJoinPoint  可以控制是否调用目标方法 只能用到环绕通知方法中
 * */
public class MyAdvice {

	public void before(JoinPoint joinpoint){
		System.out.println("前置通知:"+joinpoint.getTarget());
	}
	public void afterReturn(JoinPoint joinpoint){
		System.out.println("后置通知:"+joinpoint.getSignature());
	}
	public void after(){
		System.out.println("最终增强");
	}
	public void around(ProceedingJoinPoint pjo){
		System.out.println("环绕=-=后置通知:"+pjo.getSignature().getName());
		try{
			Object o =pjo.proceed();
			System.out.println("环绕---"+o);
		}catch(Throwable e){
			e.printStackTrace();
		}
		
		System.out.println("环绕===后置通知:"+pjo.getSignature().getName());
	}
	public void throwsAdvice(Throwable throwable){
		System.out.println("异常通知"+throwable.getMessage());
	}
}

                                                 spring-di.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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">
<!-- aspectj方式实现aop -->
<bean id="bookService" class="aspectj.BookServiceImpl"></bean>
<!-- 配置增强类 -->
<bean id="myAdvice" class="aspectj.MyAdvice"></bean>
<aop:config>
    <aop:pointcut expression="execution(* aspectj.*Impl.*(..))" id="mypointcut"></aop:pointcut>
    <aop:aspect ref="myAdvice">
    <aop:before method="before" pointcut-ref="mypointcut"/>
    <aop:after method="after" pointcut-ref="mypointcut"/>
    <aop:around method="around" pointcut-ref="mypointcut"/>
    <aop:after-throwing method="throwsAdvice" pointcut-ref="mypointcut" throwing="throwable"/>
    <aop:after-returning method="afterReturn" pointcut-ref="mypointcut"/>
     </aop:aspect>
</aop:config>
</beans>

                                                 测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:aspectj/spring-di.xml")
public class TestAspectj {
	@Autowired
private BookService bookService;
@Test
public void test(){
	bookService.add();
}
}

总结:如果是环绕增强的方法必须传递参数:ProccedingJoinpoint

IIII.spring的全自动和aspectj方式实现的aop

     1)spring全自动的增强类需要实现aop联盟提供的几个接口:MethodInterceptor(环绕),MethodBeforeAdvice(前置),AfterReturningAdvice(后置)

   spring配置文件使用的是:<aop:advisor>节点配置

   2)aspectj方式

   增强类不需要实现任何接口,只需要提供几个用于增强的方法即可

   注意:如果是环绕增强的方法必须传递参数:ProccedingJoinpoint

        其他增强可传入JoinPoint参数(aspect包下的),该参数可获得目标方法的基本信息

在spring配置文件中使用<aop:aspect>节点配置

 8、2 基于注解

  增强类:

@Aspect   //该注解等价于 xml<bean id="myAdvice" class="aspectj.MyAdvice"></bean>
@Component
public class MyAdvice {
 @Pointcut(value="execution(* aspectj.annotation.*Impl.*(..))")
	public void myPointcut(){
		
	}
	@Before(value="myPointcut()")
	public void before(JoinPoint joinpoint){
		System.out.println("前置通知:"+joinpoint.getTarget());
	}
	@AfterReturning("myPointcut()")
	public void afterReturn(JoinPoint joinpoint){
		System.out.println("后置通知:"+joinpoint.getSignature());
	}
	@After("myPointcut()")
	public void after(){
		System.out.println("最终增强");
	}
	@Around("myPointcut()")
	public void around(ProceedingJoinPoint pjo){
		System.out.println("环绕=-=后置通知:"+pjo.getSignature().getName());
		try{
			Object o =pjo.proceed();
			System.out.println("环绕---"+o);
		}catch(Throwable e){
			e.printStackTrace();
		}
		
		System.out.println("环绕===后置通知:"+pjo.getSignature().getName());
	}
	//异常:添加:throwing="throwable"  值为参数名称
	@AfterThrowing(value="myPointcut()",throwing="throwable")
	public void throwsAdvice(Throwable throwable){
		System.out.println("异常通知"+throwable.getMessage());
	}
}

spring-di.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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="aspectj.annotation"></context:component-scan>
<!-- aop自动代理 
proxy-target-class="false" 默认jdk创建代理对象
                 true :cglib创建代理对象
-->
<aop:aspectj-autoproxy proxy-target-class="false"></aop:aspectj-autoproxy>
</beans>

测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/aspectj/annotation/spring-di.xml")
public class TestAnnotaiont {
	@Resource
	private BookService bookService;
	@Test
	public void test(){
		//System.out.println(bookService);
		bookService.add();
	}
}

BookServiceImpl不要忘记加注解@Service

猜你喜欢

转载自blog.csdn.net/weixin_42496678/article/details/82823460
今日推荐