• Spring之AOP


    AOP中关键性概念

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

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

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

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

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

    适配器(Advisor):适配器=通知(Advice)+切入点(Pointcut)

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

    v1.0 只是实现了功能
    biz
    add(){

    dao.add();

    }

    del(){
    dao.del();
    }

    v2.0
    浏览器调用了用户的新增、删除方法,客户需要知道是那个用户被删除了,是由谁删除了

    新建日志表t_log
    biz
    add(){
    logDao.add(session.get("current_user"),user);
    dao.add(user);

    }

    del(){
    logDao.add(session.get("current_user"),user);
    dao.del();
    }

    edit(){
    logDao.add(session.get("current_user"),user);
    dao.del();
    }
    .....


    v2.0
    浏览器调用了xxx的新增、删除方法,客户需要知道是那个用户被删除了,是由谁删除了

    aop:
    不改动原有代码,实现日志添加功能

    1. AOP
    即面向切面编程


    2. AOP带来的好处
    让我们可以 “专心做事”
    案例:
    public void doSameBusiness (long lParam,String sParam){
    // 记录日志
    log.info("调用 doSameBusiness方法,参数是:"+lParam);
    // 输入合法性验证
    if (lParam<=0){
    throws new IllegalArgumentException("xx应该大于0");
    }
    if (sParam==null || sParam.trim().equals("")){
    throws new IllegalArgumentException("xx不能为空");
    }
    // 异常处理
    try{ ...
    }catch(...){
    }catch(...){
    }
    // 事务控制
    tx.commit();
    }


    3 工具类org.springframework.aop.framework.ProxyFactoryBean用来创建一个代理对象,在一般情况下它需要注入以下三个属性:
    proxyInterfaces:代理应该实现的接口列表(List)
    interceptorNames:需要应用到目标对象上的通知Bean的名字。(List)
    target:目标对象 (Object)

    IBookBiz

    package com.zl.aop.biz;
    
    public interface IBookBiz {
    	// 购书
    	public boolean buy(String userName, String bookName, Double price);
    
    
    	// 发表书评
    	public void comment(String userName, String comments);
    }
    

      

    BookBizImpl

    package com.zl.aop.biz.impl;
    
    import com.zl.aop.biz.IBookBiz;
    import com.zl.aop.exception.PriceException;
    
    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);
    	}
    
    
    }
    

      

    PriceException

    package com.zl.aop.exception;
    
    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);
    	}
    	
    }
      
    

      

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

    MethodBeforeAdvice

    package com.zl.advice;
    
    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[] args, Object target) throws Throwable {
    		// TODO Auto-generated method stub
    		String clzName=target.getClass().getName();
    		String methodName=method.getName();
    		String params=Arrays.toString(args);
    		System.out.println("[买书、评论前加系统日志]:"+clzName+"."+methodName+"("+params  +")");
    	}
    
    }
    

      


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

    MyAfterReturningAdvice

    package com.zl.aop.advice;
    
    import java.lang.reflect.Method;
    import java.util.Arrays;
    
    import org.springframework.aop.AfterReturningAdvice;
    
    /**
     * 后置通知(买书返利(存在bug))
     * @author zl
     *
     */
    public class MyAfterReturningAdvice implements AfterReturningAdvice {
    
    	@Override
    	public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
    		String clzName = target.getClass().getName();
    		String methodName = method.getName();
    		String  params = Arrays.toString(args);
    		System.out.println("【买书返利后置通知】:" + clzName +"." + methodName + "("+params+")"+"	 目标对象方法调用后的返回值"+returnValue);
    		
    	}
    
    }
    

      


    6. 环绕通知(org.aopalliance.intercept.MethodInterceptor):包围一个连接点的通知,最大特点是可以修改返回值,由于它在方法前后都加入了自己的逻辑代码,因此功能异常强大。
    它通过MethodInvocation.proceed()来调用目标方法(甚至可以不调用,这样目标方法就不会执行)
    案例:修改日志系统不光要输出参数,还要输出返回值(环绕通知)

    MyMethodInterceptor

    package com.zl.aop.advice;
    
    import java.util.Arrays;
    
    import org.aopalliance.intercept.MethodInterceptor;
    import org.aopalliance.intercept.MethodInvocation;
    
    /**
     * 环绕通知
     * @author zl
     *
     */
    public class MyMethodInterceptor implements MethodInterceptor {
    
    	@Override
    	public Object invoke(MethodInvocation invocation) throws Throwable {
    		String clzName = invocation.getThis().getClass().getName();
    		String methodName = invocation.getMethod().getName();
    		String  params = Arrays.toString(invocation.getArguments());
    //		sessionFactory.openSession,session.beginTransaction
    		Object returnValue = invocation.proceed();
    		System.out.println("【环绕通知】:" + clzName +"." + methodName + "("+params+")" + "	 目标对象方法调用后的返回值" + returnValue);
    //		transaction.commit(),session.close
    //		System.out.println("	 目标对象方法调用后的返回值"+returnValue);
    		
    		return returnValue;
    	}
    
    }
    

      

    7. 异常通知(org.springframework.aop.ThrowsAdvice):这个通知会在方法抛出异常退出时执行
    案例: 书本价格为负数时抛出一个异常,通过异常通知取消此订单

    MyThrowsAdvice

    package com.zl.aop.advice;
    
    import org.springframework.aop.ThrowsAdvice;
    
    import com.zl.aop.exception.PriceException;
    
    /**
     * 异常通知
     *   案例:
     *       张三向李四转账
     *       biz.transfer(user1,user2)
     *       UserDao.update(user1)
     *       UserDao.update(user2)
     * @author zl
     * 
     *
     */
    public class MyThrowsAdvice implements ThrowsAdvice {
    
    	public void afterThrowing( PriceException ex ) {
    		System.out.println("价格输入有误,购买失败,请重新输入!!!");
    	}
    }
    

      

    8. 适配器(org.springframework.aop.support.RegexpMethodPointcutAdvisor) 适配器=通知(Advice)+切入点(Pointcut)
    案例:通过适配器解决发书评时也返利的问题
    .*buy

    spring-context.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"
    	default-autowire="byType"
    	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">
    	
    	<bean class="com.zl.ioc.biz.imp.UserBizImpl2" id="userBiz"></bean>
    	
    	<bean class="com.zl.ioc.web.UserAction" id="xxx">
    	      <!-- set注入用property标签 -->
    	      <property name="userBiz" ref="userBiz"></property>
    	     <!--  <property name="uname" value="zs"></property>
    	      <property name="age" value="22"></property> -->
    	      <!-- 构造注入用constructor-arg标签 -->
    	      <constructor-arg name="uname" value="ls"></constructor-arg>
    	      <constructor-arg name="age"  value="18"></constructor-arg>
    	      <property name="hobby">
    	           <list>
    	               <value>篮球</value>
    	               <value>RAP</value>
    	               <value>唱</value>
    	           </list>
    	      </property>
    	</bean>
    	
    	<bean class="com.zl.ioc.web.OrderAction" id="ttt">
    	     <!--  <property name="userBiz" ref="userBiz"></property> -->
    	</bean>
    	
    	<!-- *************AOP**************** -->
    	
    	<!-- 目标对象 -->
    	<bean id="bookBiz" class="com.zl.aop.biz.impl.BookBizImpl"></bean>
    	<!-- 前置通知  -->
    	<bean id="myBefore" class="com.zl.aop.advice.MyMethodBeforeAdvice"></bean>
    	<!-- 后置通知  -->
    	<bean id="myAfter" class="com.zl.aop.advice.MyAfterReturningAdvice"></bean>
        <!-- 环绕通知  -->
    	<bean id="myInterceptor" class="com.zl.aop.advice.MyMethodInterceptor"></bean>
    	<!-- 异常通知  -->
    	<bean id="myThrowsAdvice" class="com.zl.aop.advice.MyThrowsAdvice"></bean>
    	<!-- 过滤通知  -->
    	<bean id="myAfter2" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
    	    <property name="advice" ref="myAfter"></property>
    	    <property name="pattern" value=".*buy"></property>
    	</bean>
    	
    	<!-- 由代理工厂来组装目标对象及通知 -->
    	<bean id="bookProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
    	     <property name="target" ref="bookBiz"></property>
    	     <property name="proxyInterfaces">
    	          <list>
    	               <value>com.zl.aop.biz.IBookBiz</value>
    	          </list>
    	     </property>
    	     <property name="interceptorNames">
    	          <list>
    	              <value>myBefore</value>
    	              <!-- <value>myAfter</value> -->
    	              <value>myAfter2</value>
    	              <value>myInterceptor</value>
    	              <value>myThrowsAdvice</value>
    	          </list>
    	     </property>
    	</bean>
    </beans>
    

      

    AopTest

    package com.zl.aop.test;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import com.zl.aop.biz.IBookBiz;
    import com.zl.ioc.web.UserAction;
    
    public class AopTest {
    
    	public static void main(String[] args) {
    		ApplicationContext springConttext = new ClassPathXmlApplicationContext("/spring-context.xml");
    		IBookBiz bean = (IBookBiz) springConttext.getBean("bookProxy");
    		System.out.println(bean.getClass());
    		boolean buy = bean.buy("张三", "后来的我们都哭了", 66d);
    		bean.comment("张三", "哈哈哈哈");
    	}
    }
    

      

  • 相关阅读:
    react路由(标签属性、Hooks、路由跳转、传值、守卫、懒加载)总结大全
    react嵌套路由(结合新版Hooks-useRouteMatch, useParams)
    react 路由封装使用(同vue)
    【转载】最小割
    专题训练之最大流
    服务器版本更新与客户端不同步的问题
    springboot整合mq接收消息队列
    跨域问题的解决方案
    1小时轻松上手springmvc,视频网站后台开发
    linux部署服务器遇到tomcat already start
  • 原文地址:https://www.cnblogs.com/BAYOUA/p/11350576.html
Copyright © 2020-2023  润新知