栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring之aop

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring之aop

一、AOP中关键性概念

连接点(Joinpoint):程序执行过程中明确的点,如方法的调用,或者异常的抛出.

目标(Target):被通知(被代理)的对象 注1:完成具体的业务逻辑

通知(Advice):在某个特定的连接点上执行的动作,同时Advice也是程序代码的具体实现,例如一个实现日志记录的代码(通知有些书上也称为处理) 注2:完成切面编程

代理(Proxy):将通知应用到目标对象后创建的对象(代理=目标+通知), 例子:外科医生+护士 注3:只有代理对象才有AOP功能,而AOP的代码是写在通知的方法里面的

切入点(Pointcut):多个连接点的集合,定义了通知应该应用到那些连接点。 (也将Pointcut理解成一个条件 ,此条件决定了容器在什么情况下将通知和目标组合成代理返回给外部程序) 适配器(Advisor):适配器=通知(Advice)+切入点(Pointcut)

3 工具类org.springframework.aop.framework.ProxyFactoryBean用来创建一个代理对象,在一般情况下它需要注入以下三个属性:

proxyInterfaces:代理应该实现的接口列表(List)

interceptorNames:需要应用到目标对象上的通知Bean的名字。

(List) target:目标对象 (Object)

如何实现AOP

AOP 即面向切面编程

目标对象只负责业务逻辑代码 通知对象负责AOP代码,这二个对象都没有AOP的功能,只有代理对象才有

二、前置通知

前置通知的价值在于:创建session,开启事务

在连接点之前执行的通知() 案例:在购书系统当中使用AOP方式实现日志系统

IBookBiz
package com.dhm.aop.Biz;

public interface IBookBiz {
	// 购书
	public boolean buy(String userName, String bookName, Double price);

	// 发表书评
	public void comment(String userName, String comments);
}
PriceException继承RuntimeException
package com.dhm.aop.Biz;

public class PriceException extends RuntimeException {

	public PriceException() {
		super();
	}

	public PriceException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
	}

	public PriceException(String message, Throwable cause) {
		super(message, cause);
	}

	public PriceException(String message) {
		super(message);
	}

	public PriceException(Throwable cause) {
		super(cause);
	}
	
}
MyMethodBeforeAdvice实现MethodBeforeAdvice

target:目标对象
method:被触发的目标对象的方法
args:目标对象的目标方法的携带的参数

package com.dhm.aop.Biz;

import java.lang.reflect.Method;
import java.util.Arrays;

import org.springframework.aop.MethodBeforeAdvice;

public class MyMethodBeforeAdvice implements MethodBeforeAdvice{

	@Override
	public void before(Method method, Object[] arg1, Object target) throws Throwable {
		String clzName=target.getClass().getName();
		String methodName=method.getName();
		String params=Arrays.toString(arg1);
		System.out.println("【系统日志】:正在调用"+clzName+"."+methodName+"("+params+")");
		
	}

	
}
BookBizImpl实现IBookBiz
package com.dhm.aop.Biz;

public class BookBizImpl implements IBookBiz {

	public BookBizImpl() {
		super();
	}

	public boolean buy(String userName, String bookName, Double price) {
		// 通过控制台的输出方式模拟购书
		if (null == price || price <= 0) {
			throw new PriceException("book price exception");
		}
		System.out.println(userName + " buy " + bookName + ", spend " + price);
		return true;
	}

	public void comment(String userName, String comments) {
		// 通过控制台的输出方式模拟发表书评
		System.out.println(userName + " say:" + comments);
	}

}
spring-context.xml


    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    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-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">




     




     
     
     
         
               
               
         

     








     
     
     
     com.dhm.aop.Biz.IBookBiz
     

     

     
     
     myBefore
     

     

     

测试及结果

package com.dhm.aop.Biz;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AopTest {
       public static void main(String[] args) {
            ApplicationContext applicationContext=new ClassPathXmlApplicationContext("/spring-context.xml");
            IBookBiz bookBiz=(IBookBiz) applicationContext.getBean("bookProxy");

//            这个buy是先去获取前置通知的代码,再去调用目标对象的业务代码
            bookBiz.buy("小戴", "小米的余生", 22.4d);
            bookBiz.comment("小戴", "给我整不会了");
        }       }

 三、后置通知

 后置通知一般放在方法结尾,比前置通知多了一个返回值

后置通知价值在于:提交事务,关闭session

在连接点正常完成后执行的通知 案例:在线购书系统中,要求不修改BookBizImpl代码的情况下增加如下功能:对买书的用户进行返利:每买本书返利3元。(后置通知) 即:每调用一次buy方法打印:“销售返利返利3元。”

spring-context.xml





     
     
     
     com.dhm.aop.Biz.IBookBiz
     

     

     
     
     myBefore
      myAfter
     

     

     

MyAfterReturningAdvice 实现AfterReturningAdvice
package com.dhm.aop.Biz;

import java.lang.reflect.Method;
import java.util.Arrays;

import org.springframework.aop.AfterReturningAdvice;

public class MyAfterReturningAdvice implements AfterReturningAdvice{

	@Override
	public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
		String targetName = target.getClass().getName();
		String methodName = method.getName();
		String params = Arrays.toString(args);
		String msg = "【返利通知:返利3元】:正在调用->" + targetName + "." + methodName + ",携带的参数:" + params + ";目标对象所调用的方法的返回值:"
				+ returnValue;
		System.out.println(msg);
		
	}
}

 四、环绕通知

包含了前置和后置

包围一个连接点的通知,最大特点是可以修改返回值,由于它在方法前后都加入了自己的逻辑代码,因此功能异常强大。 它通过MethodInvocation.proceed()来调用目标方法(甚至可以不调用,这样目标方法就不会执行)

案例:修改日志系统不光要输出参数,还要输出返回值(环绕通知)

spring-context.xml




     
     
     
     com.dhm.aop.Biz.IBookBiz
     

     

     
     
     myBefore
      myAfter
      myFilterAdvice
     

     

     

MyMethodInterceptor 实现MethodInterceptor
package com.dhm.aop.Biz;

import java.lang.reflect.Method;
import java.util.Arrays;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class MyMethodInterceptor implements MethodInterceptor{
//	invocation:可以执行被代理的目标对象的业务方法
public Object invoke(MethodInvocation invocation) throws Throwable {
	Object target = invocation.getThis();
	Method method = invocation.getMethod();
	Object[] args = invocation.getArguments();
	// a.jsp window.open(b.jsp)
	// b.jsp xxx->返回object->b.jsp window.close();window.getArguments;
	String targetName = target.getClass().getName();
	String methodName = method.getName();
	String params = Arrays.toString(args);
	String msg = "【环绕通知】:正在调用->" + targetName + "." + methodName + ",携带的参数:" + params;
	System.out.println(msg);
	Object returnValue = invocation.proceed();
	String msg2 = "【环绕通知】:目标对象所调用的方法的返回值:" + returnValue;
	System.out.println(msg2);
	return returnValue;
}
}

 五、异常通知

这个通知会在方法抛出异常退出时执行

案例: 书本价格为负数时抛出一个异常,通过异常通知取消此订单

spring-context.xml





     
     
     
     com.dhm.aop.Biz.IBookBiz
     

     

     
     
     myBefore
      myAfter
      myFilterAdvice
      myExceptionAdvice
     

     

     

MyThrowsAdvice 实现 ThrowsAdvice
package com.dhm.aop.Biz;

import org.springframework.aop.ThrowsAdvice;

public class MyThrowsAdvice implements ThrowsAdvice{
	public void afterThrowing( PriceException ex ) {
		System.out.println("价格输入有误,购买失败,请重新输入!!!");
	}

}
将价格改为负数,进入异常通知

 六、过滤通知 spring-context.xml

   过滤具有后置通知的buy方法、del方法

 
            id="myAfter2">
       
       
       
       
           
                .*buy
                .*del
           

       




     
     
     
     com.dhm.aop.Biz.IBookBiz
     

     

     
     
     myBefore
      myAfter
      myFilterAdvice
      myExceptionAdvice
        myAfter2
     

     

     

---------------------没有了-------------------------------------------- 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/349262.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号