spring-aop

AOP简介:

在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

 AOP中关键性概念

   连接点(Joinpoint):程序执行过程中明确的点,如方法的调用,或者异常的抛出.
  目标(Target):被通知(被代理)的对象
     注1:完成具体的业务逻辑
  通知(Advice):在某个特定的连接点上执行的动作,同时Advice也是程序代码的具体实现,例如一个实现日志记录的代码(通知有些书上也称为处理)
     注2:完成切面编程
  代理(Proxy):将通知应用到目标对象后创建的对象(代理=目标+通知),
             例子:外科医生+护士
     注3:只有代理对象才有AOP功能,而AOP的代码是写在通知的方法里面的
  切入点(Pointcut):多个连接点的集合,定义了通知应该应用到那些连接点。
                 (也将Pointcut理解成一个条件 ,此条件决定了容器在什么情况下将通知和目标组合成代理返回给外部程序)
    
  适配器(Advisor):适配器=通知(Advice)+切入点(Pointcut)
 
代码演示:

IBookBiz 
package com.hxc.aop.biz;

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

    // 发表书评
    public void comment(String userName, String comments);
}
BookBizImpl 
package com.hxc.aop.biz.impl;

import com.hxc.aop.biz.IBookBiz;
import com.hxc.aop.ex.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.hxc.aop.ex;

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 
package com.hxc.aop.advice;

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

import org.springframework.aop.MethodBeforeAdvice;

/**
 * 买书,评论前的系统日志
 * 
 * @author 旧城
 *
 */
public class MyMethodBeforeAdvice implements MethodBeforeAdvice {

    @Override
    public void before(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 + ")");

    }

}
MyMethodInterceptor 
package com.hxc.aop.advice;

import java.util.Arrays;

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

/**
 * 
 * @author 旧城
 *
 */
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.beginTransation
        System.out.println("【环绕通知】:"+clzName+"."+methodName+"("+params+")");
        Object returnValue=invocation.proceed();
//        transation.commit().session.close
        System.out.println("【环绕通知】:	 目标对象方法调用后的返回值"+returnValue);
        return returnValue;
    }

}
MyThrowsAdvice
package com.hxc.aop.advice;

import org.springframework.aop.ThrowsAdvice;

import com.hxc.aop.ex.PriceException;

/**
 * 异常通知
 * @author Administrator
 *
 */
public class MyThrowsAdvice implements ThrowsAdvice {
    public void afterThrowing( PriceException ex ) {
        System.out.println("价格输入有误,购买失败,请重新输入!!!");
    }
}
MyAfterReturningAdvice 
package com.hxc.aop.advice;

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

import org.springframework.aop.AfterReturningAdvice;
/**
 * 买书返利(存在bug)
 * @author 旧城
 *
 */
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);
    }

}

配置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:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
       
       <bean class="com.hxc.ioc.impl.UserBizImpl2" id="userBiz"></bean>
      
       <bean class="com.hxc.ioc.web.UserAction" id="user">
               
               <!-- set注入用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="22"></constructor-arg>
           
            <property name="hobby" >
                <list>
                    <value></value>
                    <value></value>
                    <value>rap</value>
                    <value>篮球</value>
                </list>
            </property>
       </bean>
       
       
       <bean class="com.hxc.ioc.web.OrderAction" id="ttt">
            
       </bean>
       <!-- **************************AOP**************************** -->
       <!-- 目标对象 -->
       <bean id="bookBiz" class="com.hxc.aop.biz.impl.BookBizImpl"></bean>
       <!-- 通知 -->
       <bean id="myBefore" class="com.hxc.aop.advice.MyMethodBeforeAdvice"></bean>
       <bean id="myAfter" class="com.hxc.aop.advice.MyAfterReturningAdvice"></bean>
       <bean id="myInterceptor" class="com.hxc.aop.advice.MyMethodInterceptor"></bean>
       <bean id="myThrowsAdvice" class="com.hxc.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.hxc.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.hxc.aop.test;

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

import com.hxc.aop.biz.IBookBiz;

public class AopTest {

    public static void main(String[] args) {

        ApplicationContext springContext=new ClassPathXmlApplicationContext("/spring-context.xml");
        IBookBiz bean=(IBookBiz) springContext.getBean("bookProxy");
        System.out.println(bean.getClass());
        boolean buy= bean.buy("某坤", "篮球入门手册", 66d);
        bean.comment("某坤", "我喜欢唱跳rap篮球");
    }
}

效果如下:

原文地址:https://www.cnblogs.com/huxiaocong/p/11360216.html