Spring之AOP

首先我们先来导入一些需要的类

 IBookBiz.java

package com.jt.aop.biz;

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

    // 发表书评
    public void comment(String userName, String comments)
}

 BookBizImpl.java

package com.jt.aop.biz.impl;

import com.jt.aop.biz.IBookBiz;
import com.jt.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.java

package com.jt.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);
    }
    
}

测试类

AopTest.java

package com.jt.aop.test;

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

import com.jt.aop.biz.IBookBiz;
import com.jt.ioc.web.OrderAction;
import com.jt.ioc.web.UserAction;


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("jt","圣墟",-66d);
        bean.comment("jt","非常好看");
    }
}

接下来就是前置通知

MyMethodBeforeAdvice.java

package com.jt.aop.advice;

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

import org.springframework.aop.MethodBeforeAdvice;
/**
 * 买书,评论前加系统日志
 * @author jt
 *
 */
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+")");
    }
}

后置通知MyAfterReturningAdvice.java

package com.jt.aop.advice;

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

/**
 * 买书返利(存在BUG)
 */
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 clzName=target.getClass().getName();
        String methodName=method.getName();
        String params=Arrays.toString(args);
        System.out.println("[买书返利的后置通知]:"+clzName+"."+methodName+"("+params+")"+"	 目标对象方法调用后的返回值"+returnValue);
    }

}

环绕通知MyMethodInterceptor.java

package com.jt.aop.advice;

import java.util.Arrays;

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

public class MyMethodInterceptor implements MethodInterceptor {

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        String clzName=invocation.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.java

package com.jt.aop.advice;

import org.springframework.aop.ThrowsAdvice;

import com.jt.aop.ex.PriceException;
/**
 * 异常通知
 * @author jt
 *案例:张三向李四转账
 *   biz.transfer(user1,user2)
 *      UserDao.update(user1)
 *       UserDao.update(user2)
 *      
 *   
 */
public class MyThrowsAdvice implements ThrowsAdvice {

    public void afterThrowing(PriceException ex) {
        System.out.println("价格输入有误,购买失败");
    }
}

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="byName"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<bean class="com.jt.ioc.biz.impl.UserBizImpl2" id="userBiz"></bean>
<bean class="com.jt.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> -->
  <!--set注入用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>rap</value>
            <value>跳舞</value>
       </list>
  
  </property>
</bean>
<bean class="com.jt.ioc.web.OrderAction" id="ttt">
  <property name="userBiz" ref="userBiz"></property>
</bean>
<!--*********************************************************************  -->
<!--目标对象  -->
<bean id="bookBiz" class="com.jt.aop.biz.impl.BookBizImpl"></bean>
<!-- 前置通知  -->
<bean id="myBefore" class="com.jt.aop.advice.MyMethodBeforeAdvice"></bean>
<!-- 后置通知  -->
<bean id="myAfter" class="com.jt.aop.advice.MyAfterReturningAdvice"></bean>
<!-- 环绕通知  -->
<bean id="myInterceptor" class="com.jt.aop.advice.MyMethodInterceptor"></bean>
<!-- 异常通知  -->
<bean id="myThrowsAdvice" class="com.jt.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.jt.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>

今天的博客就到此结束了

原文地址:https://www.cnblogs.com/ztbk/p/11355198.html